CSE 2D Array
CSE 2D Array
2D array
2D array
float x[3][4];
here, x is a 2D array. It can have 12 elements. The array can be
considered as a table shown below.
Index of a 2D array
2D array example
#include <stdio.h> Output:
int main () { a[0][0]: 0
/* an array with 5 rows and 2 columns*/ a[0][1]: 0
int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}}; a[1][0]: 1
int i, j; a[1][1]: 2
/* output each array element's value */ a[2][0]: 2
for ( i = 0; i < 5; i++ ) { a[2][1]: 4
for ( j = 0; j < 2; j++ ) { a[3][0]: 3
printf("a[%d][%d] = %d\n", i,j, a[i][j] ); a[3][1]: 6
} a[4][0]: 4
a[4][1]: 8
}
return 0;
}
2D array problems
1. Write a program in C for addition of two Matrices of same size.
2. Write a program in C for subtraction of two Matrices.
3. Write a program in C to find transpose of a given matrix.
4. Write a program in C to find sum of right diagonals of a matrix.
5. Write a program in C to find sum of left diagonals of a matrix.
6. Write a program in C to print or display upper triangular matrix.
7. Write a program in C to print or display lower triangular matrix.
1 C program for addition of two Matrices of same size
1 Addition of two Matrices of the same size
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
sum[i][j]=arr1[i][j]+arr2[i][j];
}
}
2 Subtraction of two Matrices of the same size
Now, change the previous program to subtract two matrices of the same size
3 Transpose of a matrix
3 C program to find transpose of a given matrix
for(i=0;i<row;i++)
{
for(j=0;j<column;j++)
{
transpose[j][i]=array[i][j];
}
}
4 Sum of right diagonals of a matrix
Right diagonal
Left diagonal
4 C program to find the sum of right diagonals of a matrix
sum = 0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if (i==j)
sum= sum+array[i][j];
}
}
5 Sum of left diagonals of a matrix
Right diagonal
Left diagonal
5 C program to find the sum of left diagonals of a matrix