In groups of 2 or 3, write a C program the creates and initialises a 2D array wi
ID: 3923094 • Letter: I
Question
In groups of 2 or 3, write a C program the creates and initialises a 2D array with 4 rows and 4 columns. This array can be initialised with any values you choose. The program should then calculate the sum of all elements on the diagonal of the array. For example if the following array is created: 1 2 3 4 5 6 7 8 8 7 6 5 4 3 2 1 Then you program should calculate the sum of the highlighted diagonal elements and provide an answer of 14. Now write another program which calculates the sum of the opposite diagonal: 1 2 3 4 5 6 7 8 8 7 6 5 4 3 2 1 yielding (in this example), 22. Note that you do NOT have to make this code into a function. Also, it should be general enough to work with any square array.
Explanation / Answer
#include <stdio.h>
int main(void) {
int a[10][10];
int i,j,n;
int sumDiagonal=0;
int sumDiagonalRev=0;
printf("Enter the rows and columns of square array , rows=columns ");
scanf("%d",&n);
printf("Enter the elements of array a[n][n] "); //input 2 dimensional array i is row and j is column
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
for(i=0;i<n;i++) //print the array
{
for(j=0;j<n;j++)
{
printf("%d ",a[i][j]);
}
printf(" ");
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(i==j) //a[0][0],a[1][1],a[2][2].a[3][3] i=j
sumDiagonal=sumDiagonal+a[i][j];
}
printf(" Sum of Diagonal elements in order =%d",sumDiagonal);
for(i=n;i>=0;i--)
for(j=n;j>=0;j--)
{
if(i+j==3) //a[0][3],a[1][2],a[2][1],a[3][0] , i+j=3
{
sumDiagonalRev=sumDiagonalRev+a[i][j];
}
}
printf(" Sum of Diagonal elements in reverse order =%d",sumDiagonalRev);
return 0;
}
Output:
Success time: 0 memory: 2172 signal:0