Module 8 - Arrays in C
Module 8 - Arrays in C
Intro to Arrays in C
What are Arrays?
• Array – fixed size sequenced collection of elements of the same data type.
• It is a derived data type.
• Example:
• int arr[10] declares an array of 10 elements each of integer type
arr
10 integer elements
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Defining Arrays
Syntax:
<Storage-class> <data-type> <array_name>[<size>]
Examples:
int count[100];
char name[25];
float cgpa[50];
Good practice:
#define SIZE 100
int count[SIZE];
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Initializing arrays
Few valid ways of initializing arrays in C
1 2 3 4 5 6
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Accessing elements of an array
int arr[10];
arr
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example
A program that takes 10 elements from the user and stores them in
an array and then computes their sum.
#include <stdio.h>
int main(){
int nums[10]; int sum=0; int i;
for(i=0; i<10; i++){
scanf(“%d”,&nums[i]);
}
for(i=0;i<10;i++){
sum = sum + nums[i];
}
printf(“The sum is: %d”, sum);
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Arrays in Memory
Arrays in memory
…
return 0;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Addresses in Main Memory
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Addresses in Main Memory
Addresses • Note: our memory is byte
10010000 addressable.
10010001 o every byte in the memory has an
10010010
10010011
address,
10010100 o In other words, size of each
10010101 memory location is 1 byte.
• For Simplicity let us consider each
address in the main memory to be
represented by 8 bits.
• The addresses of the memory
locations are depicted in the figure
10011101
10011110
• Note:The addresses of two contiguous
locations differ by 1 (in binary)
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
How is an array stored in main
memory?
Consider this program:
Addresses
int main(){
10010000
int arr[4] = {1, 2, 3, 4};
10010001
10010010 …
10010011 return 0;
10010100 }
10010101
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
How is an array stored in main
memory?
Consider this program:
Addresses
int main(){
10010000
int arr[4] = {1, 2, 3, 4};
10010001
10010010 …
10010011 return 0;
10010100 }
10010101
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
How is an array stored in main
memory?
int arr[4] = {1, 2, 3, 4}; Addresses
10010000
10010001
Stores first element of arr, accessed by arr[0] 10010010
10010011
Stores second element of arr, accessed by arr[1] 10010100
10010101
Stores third element of arr, accessed by arr[2]
10011101
10011110
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
How is an array stored in main
memory?
Addresses
10010000
10010001
10010010 arr points here and contains this address
arr[0] = 1
10010011
10010100 arr+1 refers to this address
arr[1] = 2
10010101
arr+2 refers to this address
arr[2] = 3
arr+3 refers to this address
arr[3] = 4
• We are storing 2 bytes of memory at address arr
• We are storing 2 bytes of memory at address
arr+1, and so on.
• arr and arr+1 differ by one unit of space required
10011101
to store an integer, which is of 2 bytes or 2
10011110
addressable memory locations.
• If our array is storing float values, arr and arr+1
would differ by 4 bytes or 4 addressable memory
locations.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
A few examples
Example 1
int main(){
int arr[6] = {1, 2, 3, 4, 5, 6};
for(int i=0;i<sizeof(arr)/sizeof(arr[0]); i++)
printf("%d\t",arr[i]);
return 0;
}
Output?
1 2 3 4 5 6
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 2
int main(){
int arr[6] = {1, 2, 3};
for(int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
printf("%d\t",arr[i]);
return 0;
}
Output?
1 2 3 0 0 0
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 3
int main(){
int arr[] = {1, 2, 3};
for(int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
printf("%d\t",arr[i]);
return 0;
}
Output?
1 2 3
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 4
int main(){
int arr[6];
arr[6] = {1, 2, 3, 4, 5, 6};
for(int i=0;i<sizeof(arr)/sizeof(arr[0]);i++)
printf("%d\t",arr[i]);
return 0;
}
Output?
Compile-time error
What is the right way in such a scenario (declaration and initialization are separated) ?
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 5
int main(){
int arr[6];
for (int i=0;i<6;i++)
arr[i] = i;
for (int i=0;i<6;i++)
printf("%d\t",arr[i]);
return 0;
}
Output?
0 1 2 3 4 5
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 6
int main(){
int arr[6];
for (int i=0;i<6;i++)
arr[i] = i;
for (int i=0;i<9;i++)
printf("%d\t",arr[i]);
return 0;
}
Output?
0 1 2 3 4 5 3965 -8905 4872
(junk values)
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 7
int main(){ Problems with arrays – No
int arr[6]; bounds checking!!
for (int i=0;i<8;i++) • There is no check in C compiler to
see if the subscript used for an
arr[i] = i;
array exceeds the size of the array.
for (int i=0;i<6;i++) • Data entered with a subscript
printf("%d\t",arr[i]); exceeding the array size will simply
return 0; be placed in memory outside the
} array limit and lead to
unpredictable results.
• It’s the programmer’s responsibility
to take care.
Output?
*** stack smashing detected ***: ./a.out terminated
0 1 2 3 4 5 Aborted (core dumped)
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 8
int main(){
int arr[6]={0};
arr[6]= 1;
for (int i=0;i<7;i++)
printf("%d\t",arr[i]);
return 0;
}
Output?
*** stack smashing detected ***: ./a.out terminated
0 0 0 0 0 0 1
Aborted (core dumped)
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example 9
Write a C code #include<stdio.h>
which takes an int #include<stdlib.h>
array of size SIZE
#define SIZE 9
and calculates int main()
(and displays) the {
average of all int arr[SIZE], sum=0;
numbers for (int i=0;i<SIZE;i++)
arr[i] =i;
for (int i=0;i<SIZE;i++)
sum = sum + arr[i];
printf("AVG=%d\n",sum/SIZE);
return 0;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Copying Arrays
int old_value[5]={10,20,30,40,50};
int new_value[5];
How to copy the elements of old_value into new_value?
new_value = old_value;
It will not work. Why?
Question:
What is the correct way of copying arrays?
Sol:
Copy each individual element one by one
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Home Exercise
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
USING FUNCTIONS:
Write a C function that takes an int array of size SIZE and
calculates (and displays) the average of all numbers
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Solution
#define SIZE 9 When avg() is called, the address of
int avg(int n, int list[]){ the first element of the array intArr
int sum = 0; is copied into the array list.
for (int i=0;i<n;i++)
sum = sum + list[i];
return sum/n; intArray 0
}
list 1
int main(){
int intArray[SIZE], 2
int average; 3
for (int i=0;i<SIZE;i++) 4
intArray[i] = i;
5
average=avg(SIZE, intArray);
printf("Average=%d\n", average); 6
return 0; 7
} 8
Output:
Average=4 Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Slight change…
int main(){ int avg(int n, int list[])
int intArray[SIZE], average; {
for (int i=0;i<SIZE;i++){ int sum = 0;
intArray[i] = i; for (int i=0;i<n;i++){
printf(“%d\t”,intArray[i]); list[i] = list[i]*2
} sum = sum + list[i];
}
average=avg(SIZE,intArray); return sum/n;
printf("Average=%d\n", average); }
printf(“After calling avg…\n”);
Output:
for (int i=0;i<SIZE;i++) 0 1 2 3 4 5 6 7 8
printf(“%d\t”,intArray[i]); Average = 8
return 0; After calling avg…
} 0 2 4 6 8 10 12 14 16
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Arguments to functions
Ordinary variables are passed by value
– Values of the variables passed are copied into local variables of the
function
However… when an array is passed to a function
– Values of the array are NOT passed
– Array name interpreted as the address of the first element of the array
is passed [Pass by reference]
– This value is captured by the corresponding function parameter, which
becomes a Pointer to the first element of the array that was passed to it.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Can we ‘return’ an array from a
function?
If the array is defined inside the function, returning the array would
give run-time error.
• Why?
• Try this! Next Slide.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Let us try to explain with our
memory diagram
Stack frame allocated to When f1() returns, the memory
main_arr
main() in stack allocated to it is destroyed.
Stack
int main(){
int main_arr[] = f1();
printf(”First ele is: %d”, main_arr[0]);
Text
return 0;
}
Memory allocated Output:
to our program Error!
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example with global arrays
#define SIZE 4
int globArray[SIZE];
// int globalArray[SIZE] = {1,2,3,4} is also allowed
int avg(){
int sum = 0;
for (int i=0;i<n;i++)
sum = sum + globArray[i];
return sum/n;
int main(){
}
int average;
for (int i=0;i<SIZE;i++)
globArray[i] = i;
average=avg();
printf("Average=%d\n", average);
return 0;
} Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Example (Worked on the Board)
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Searching in an Array
Linear search
Task: Search for an element key in the Array.
Each item in the array is examined until the desired item is found
or the end of the list is reached
Algorithm:
1. Read an array of N elements named arr[0…N-1] and search element key
2. Repeat for i=0 to i=N-1
If key equals to arr[i]
Display element found and stop
3. Display element not found
4. Stop
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Linear Search – Implementation
#include <stdio.h>
int i = 0;
pos = linearSearch(arr,10,key);
return 0;
} Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Sorting (Selection Sort)
• Selection sort is a simple sorting algorithm.
• In this algorithm, the list (or an array) is divided into two parts:
• The sorted part at the left
• The unsorted part at the right
• Initially, the sorted part at the left is empty, and the unsorted part at
the right is the full list.
• In each iteration, the smallest element from the unsorted part of the
array is added to the sorted part.
• The process continues until the unsorted part of the array is empty.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Illustrating Selection Sort
14 33 27 10 35 19 42 44
Find the minimum element in the array and bring to the 0th index of the array
14 33 27 10 35 19 42 44
Element 10 is the minimum element in the array. To bring it the 0th index, we need to
swap it with the element present at the 0th index
10 33 27 14 35 19 42 44
We can now see that the sorted portion of the array is from index 0 to 0, and the
unsorted portion of the array is from index 1 to 7.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Illustrating Selection Sort (Cont.)
10 33 27 14 35 19 42 44
Now, we have to look at the array excluding the first element (element at 0th index). In
the remaining (unsorted) portion of the array, again we will find the minimum element.
10 33 27 14 35 19 42 44
The minimum element in the unsorted portion of the array is 14 at index 3. We should
swap it with the element at index 1.
10 14 27 33 35 19 42 44
We can now see that the sorted portion of the array is from index 0 to 1, and unsorted
portion of the array is from index 2 to 7.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Illustrating Selection Sort (Cont.)
In the same way, we can continue this process. In the end, the sorted portion will be the
entire array, and the unsorted portion will be empty.
10 14 27 33 35 19 42 44
10 14 19 33 35 27 42 44
10 14 19 27 35 33 42 44
10 14 19 27 33 35 42 44
10 14 19 27 33 35 42 44
10 14 19 27 33 35 42 44
10 14 19 27 33 35 42 44
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Selection Sort: Implementation
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, min;
// Swap the min element with the first element in the unsorted subarray
int temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
} Does this function need to return
} anything?
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Selection Sort: Implementation
(contd.)
int main()
{
int a[] = {24, 36, 20, 7, 42, 19};
int size = sizeof(a) / sizeof(a[0]);
selectionSort(a, size);
return 0;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Binary Search Algorithm
Algorithm // Pre-condition: List must be sorted
• The desired item is first compared to the element in the middle of the list
Initial Array(sorted)
Let x = 4 be the element to be searched.
2. Set two pointers low and high at the lowest and the highest
positions respectively.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Illustrating Binary Search
3. Find the position of the middle element mid = (low+high)/2. The middle
element is arr[mid] = 6.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Illustrating Binary Search
7. Repeat steps 3 to 6 until low meets high.
8. x = 4 is found.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Binary Search - Code
#define Size 10
main(){ // Binary search implementation
int arr[Size], index, upper, lower, key, mid;
printf("Enter Array elements:");
for(index = 0; index<Size; index++)
scanf("%d", &arr[index]);
printf("Enter search element");
scanf("%d",&key);
upper=Size-1; lower=0;
while(lower<=upper){
mid=(lower+upper)/2;
if(key>arr[mid]) lower=mid+1;
else if(key<arr[mid]) upper=mid-1;
else{
printf("Element found at location %d", mid);
return;
}
}
printf("Element no found"); Exercise: Re-write this program to do
} the searching part with a function call.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Insert/Delete in an Array
Handling changing number of
elements in the array
Insert/Delete in an Array
• Arrays once declared they are of fixed size.
• Example:
int arr1[10]; declares an array of size 10.
We can’t store 11 elements to this array.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Insert/Delete in an Array
• Choose MAX_SIZE and declare #define MAX_SIZE 10
the array with it. #define DEFAULT_VALUE -1
• Insertions can be done as long as int main() {
the number of elements of the
array does not exceed // declare array with MAX_SIZE
MAX_SIZE. int arr[MAX_SIZE];
• Keep a count of actual number
of elements present in the array // declare a variable to keep count of
– count <= MAX_SIZE number of elements in the array
• Some positions will remain vacant. int count = 0;
We shall need to store a
DEFAULT_VALUE in those // fill all the positions with the
positions. DEFAULT_VALUE
• Keep all occupied positions for(int i=0;i<MAX_SIZE;i++){
contiguous (Unoccupied positions as
well) arr[i] = DEFAULT_VALUE;
– If MAX_SIZE is 10, count is 6, } arr at this stage
then first 6 positions of the array
should be occupied with some values … … …
and remaining 4 positions should } -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
have DEFAULT_VALUE.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Insert in an Array
#define MAX_SIZE 10
#define DEFAULT_VALUE -1
int main() {
int arr[MAX_SIZE];
int count = 0;
for(int i=0;i<MAX_SIZE;i++){ 0 1 4 9 16 25 -1 -1 -1 -1
arr[i] = DEFAULT_VALUE;
}
for(int i=0;i<MAX_SIZE;i++){
arr[i] = DEFAULT_VALUE;
}
// Insert 10 into arr, while keeping arr sorted Insert 10 here after shifting
// It should get inserted between 9 and 16. elements to the right
// What should be done ?
// Shift 25, 16, by one place towards right and
// insert 10 in the place of 16.
}
0 1 4 9 16 25 -1 -1 -1 -1
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Insertion in a sorted array
#define MAX_SIZE 10 // Now shift elements from last
#define DEFAULT_VALUE -1 occupied position until i, one
int main() { position to right
… for (int j=count-1; j>i;j--){
… arr[j+1] = arr[j];
}
int x=10; //element to be inserted // loop exits when j=i, the
position to insert x.
int i=0;
arr[j] = x; count++;
// Find the position to insert x
// x inserted at its position
for (i=0; i<count; i++){
}
if (arr[i]>=x)
break; 0 1 4 9 16 25 -1 -1 -1 -1
}
// i is the position in arr where Insert 10
x should be inserted
0 1 4 9 10 16 25 -1 -1 -1
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Delete in Array (Sorted or
unsorted)
Delete is similar to insert.
0 1 4 9 10 16 25 -1 -1 -1
0 1 4 10 16 25 -1 -1 -1 -1
Character Arrays
Character Arrays
char color[3] = “RED”; R E D
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Char Arrays
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Lower Case to Upper Case
using char array
#include <stdio.h> name[i]='\0'; ????
#include <ctype.h> size = i;
int main(){ printf("\nName is %s", name);
int size,i=0; for(i=0;i<size;i++)
char name[50]; putchar(toupper(name[i]));
name[0]=getchar(); return 0;
while(name[i]!='\n') }
{
i++;
name[i]=getchar();
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Char Arrays
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Lower Case to Upper Case
using char array
#include <stdio.h> name[i]='\0';
#include <ctype.h> size = i;
int main(){ printf("\nName is %s",name);
int size,i=0; for(i=0;i<size;i++)
char name[50]; printf(toupper(name[i]));
scanf(“%c ”,&name[0]); return 0;
while(name[i]!='\n') }
{
i++;
scanf(“%c ”,&name[i]);
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Char arrays – using gets/puts
int main() Note:
{ • It is not required to
explicitly insert “\0”
char c[20]; character at the end of
int i=0; each character array
while using gets().
printf("Enter the Name"); • It automatically adds so.
gets(c);
printf("The name is %s",c);
puts(c);
return 0;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Multi-dimensional Arrays in C
Multi-dimensional Arrays
• C supports arrays of multiple dimensions
• A basic multi-dimensional array is a 2-D array
• Also known as a matrix
type variable_name[row_size][column_size];
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Examples of 2-D Arrays
column_size=4
row_size=3
Examples:
int number[3][4]; /* 12 elements */
float number[3][2]; /* 6 elements */
char name[10][20]; /* 200 chars */
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Initializing a 2-D Array
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Incorrect Ways of Initializing 2-
D Arrays
Following initializations are not allowed
int a[3][]={2,4,6,8,10,12};
int a[][]={2,4,6,8,10,12};
Note:
• If the first bracket pair is empty, then the compiler takes the size
from the number of inner brace pairs
• If the second bracket pair is empty, the compiler throws a
compilation error!
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Accessing a 2-D Array
int a[3][4]={1,2,3,4,5,6,7,8,9,10,11,12};
for(i=0;i<3;i++)
{
for(j=0;j<4;j++)
{
printf(“%d”,a[i][j]);
}
printf(“\n”);
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Row Major vs. Column Major
Example:
int a[3][3];
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Matrix Addition
Matrix Addition and
Subtraction
Matrix Addition:
1 3 0 0 1 + 0 3 + 0 1 3
1 0 + 7 5 = 1 + 7 0 + 5 = 8 5
1 2 2 1 1 + 2 2 + 1 3 3
Matrix Subtraction:
1 3 0 0 1 - 0 3 - 0 1 3
1 0 _ 7 5 = 1 - 7 0 - 5 = -6 -5
1 2 2 1 1 - 2 2 - 1 -1 1
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Working with two dimensional Arrays
(Matrix Addition & Subtraction)
Let A[m][n] and B[p][q] be two matrices.
Algorithm Steps:
1. Read two matrices A and B, and initialize C matrix to zero
2. Repeat (3) for i=0 to m-1
3. Repeat (3.a) for j=0 to n-1
3.a) C[i][j] = A[i][j] + B[i][j]
4. Display C matrix
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Addition: Code
#define ROW 10
#define COL 10
int main(){
int M1[ROW][COL],M2[ROW][COL],M3[ROW][COL],i,j;
int row1,col1,row2,col2;
printf(“Enter row value for M1\n”);
scanf(“%d”,&row1);
printf(“Enter column value for M1\n”);
scanf(“%d”,&col1);
printf(“Enter row value for M2\n”);
scanf(“%d”,&row2)
printf(“Enter column value for M2\n”);
scanf(“%d”,&col2)
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Addition: Code (Contd.)
if(row1!=row2 || col1!=col2)
{
printf(“Invalid Input: Addition is not possible”);
return;
}
printf(“Enter data for Matrix M1\n”);
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf(“%d”,&M1[i][j]);
}
printf(“\n”);
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Addition: Code (contd.)
printf(“Enter data for Matrix M2\n”);
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf(“%d”,&M2[i][j]);
}
printf(“\n”);
}
printf(“Addition of Matrices is as follows\n”);
for(i=0;i<row2;i++)
for(j=0;j<col2;j++)
M3[i][j]= M1[i][j] + M2[i][j]);
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Addition: Code (contd.)
// display the new matrix after addition
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
printf(“%d”,M3[i][j]);
}
printf(“\n”);
}
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Matrix Multiplication
Matrix Multiplication
10 11
1 2 3
X 20 21
4 5 6
30 31
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Multiplication M1xM2
Pre-condition: Number of columns in M1 should be equal to
number of rows in M2
Algorithm Steps:
1. Read two matrices M1[m][n] and M2[n][r] and initialize
another matrix M3[m][r] for storing result
2. Repeat for i=0 to m-1
Repeat for j=0 to r-1
M3[i][j] = 0
Repeat for k=0 to n-1
M3[i][j] += M1[i][k] * M2[k][j]
3. Print matrix M3
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Multiplication: Code
#include <stdio.h>
#define row1 4
#define col1 3
#define row2 3
#define col2 4
#define row3 4
#define col3 4
void main()
{
int M1[row1][col1],M2[row2][col2],M3[row3][col3];
int i,j,k;
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Multiplication: Code
(contd.)
printf(“Enter data for Matrix M1\n”);
for(i=0;i<row1;i++)
{
for(j=0;j<col1;j++)
{
scanf(“%d”,&M1[i][j]);
}
printf(“\n”);
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Multiplication: Code
(contd.)
printf(“Enter data for Matrix M2\n”);
for(i=0;i<row2;i++)
{
for(j=0;j<col2;j++)
{
scanf(“%d”,&M2[i][j]);
}
printf(“\n”);
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Multiplication: Code
(contd.)
if (col1!= row2){
printf(“Multiplication is not possible”);
return;
}
for(i=0;i<row1;i++){
for(j=0;j<col2;j++){
M3[i][j] = 0;
for(k=0;k<col1;k++){
M3[i][j] += M1[i][k] * M2[k][j];
}
}
10 11
} 1 2 3
X 20 21
4 5 6
30 31
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Matrix Multiplication: Code
(contd.)
printf(“RESULT MATRIX IS\n ”);
for(i=0;i<row3;i++){
for(j=0;j<col3;j++){
printf(“%d”,M3[i][j]);
}
printf(“\n”);
}
return;
}
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus
Note:
• Elements are stored and accessed in a similar way as that of
2D arrays.
• They are also stored in Row Major format.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
Exercises
Q. 1 Generate Fibonacci series using Array.
Dept. of Computer Science & Information Systems, BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus