How do I write a C program reads a 5×5 two-dimensional array of integers and prints the row and column sums?
How do I write a C program that reads a 5×5 two-dimensional array of integers and then prints its row sums and column sums?
Sure, it’s easy enough. Try:
/* 5×5.c */
#include <stdio.h>
int main(void)
{
int array[5][5];
int i, j;
int sum;
for (i = 0; i < 5; ++i)
for (j = 0; j < 5; ++j)
scanf("%d", &(array[i][j]));
for (i = 0; i < 5; ++i) {
sum = 0;
for (j = 0; j < 5; ++j)
sum += array[i][j];
printf("row sum [%d][] = %d\n", i, sum);
}
for (j = 0; j < 5; ++j) {
sum = 0;
for (i = 0; i < 5; ++i)
sum += array[i][j];
printf("column sum [][%d] = %d\n", j, sum);
}
return 0;
}
And, to prove it works:
[user@ariel ~]$ ./a.out
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
row sum [0][] = 15
row sum [1][] = 15
row sum [2][] = 15
row sum [3][] = 15
row sum [4][] = 15
column sum [][0] = 5
column sum [][1] = 10
column sum [][2] = 15
column sum [][3] = 20
column sum [][4] = 25
[user@ariel ~]$
Have fun!
my program might be wrong while compiling coz i have not compiled it, but u will get the logic…Ok.
int arr1[5][5],arr2[5][5],i,j,rowSum;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
printf("Enter a number:");
scanf("%d",&arr1[i][j]);
}
}
//now accept the values for second array
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
printf("Enter a number:");
scanf("%d",&arr2[i][j]);
}
}
i=0;j=0;
for(i=0;i<5;i++)
{
rowSum=0;
for(j=0;j<5;j++)
{
rowSum+=arr1[i][j]+arr2[i][j];
}
printf("Sum of rows of both 1st and 2nd array is: %d",rowSum);
}
/*similar code you can write for column sum as well, it will be good if u try yourself, it will impower your logic building sense*/
Thanks and regards.
JGJM.
using a nested for loop
outer for loop that takes i from 1 to 5
–inner for loop that takes j from 1 to 5
—-inner statement that inputs an integer into array position i, j
summing the rows and columns is just a matter of nested for loops where you hold either the row or column constant while taking the intermediate sum
And don’t forget to use the debugger to single step through and makes sure the code is executing as intended!