Written in C++, used in code blocks. I am stuck on writing the code for the sum
ID: 3588652 • Letter: W
Question
Written in C++, used in code blocks. I am stuck on writing the code for the sum of diagonal elements. This is what i have so far.
#include <stdio.h>
#define SIZE 4
int main()
{
int A[SIZE][SIZE];
int row, col, sum = 0;
int d_sum = 0;
// Wasn't sure how to display the matrix, but I got it so you type in the table exactly how you see it and it will output everything correctly.
//This function below prints your table
printf("Enter elements in matrix of size %dx%d: ", SIZE, SIZE);
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
scanf("%d", &A[row][col]);
}
}
// This function prints all the row sums
for(row=0; row<SIZE; row++)
{
sum = 0;
for(col=0; col<SIZE; col++)
{
sum += A[row][col];
}
printf("Sum of elements of Row %d = %d ", row+1, sum);
}
// This function prints all the column sums
for(row=0; row<SIZE; row++)
{
sum = 0;
for(col=0; col<SIZE; col++)
{
sum += A[col][row];
}
printf("Sum of elements of Column %d = %d ", row+1, sum);
}
// This function prints the diagonal sum.
for(row=0; row<SIZE; row++)
{
sum =0;
for(col=0; col<SIZE;col++)
{
d_sum += A[row][col];
}
printf("Sum of diagonal elements is %d ",d_sum);
}
return 0;
}
Explanation / Answer
#include <stdio.h>
#define SIZE 4
int main()
{
int A[SIZE][SIZE];
int N[SIZE+1][SIZE+1];
int row, col, r_sum,c_sum;
int d_sum = 0;
//This function below prints your table
printf("Enter elements in matrix of size %dx%d: ", SIZE, SIZE);
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
scanf("%d", &A[row][col]);
}
}
// Print Array
for(row=0; row<SIZE; row++)
{
for(col=0; col<SIZE; col++)
{
printf(" %d ", A[row][col]);
}
printf(" ");
}
for(row=0; row<SIZE; row++)
{
r_sum = 0;
c_sum = 0;
for(col=0; col<SIZE; col++)
{
// add A elements to new Array
N[row][col] = A[row][col];
// for row sum
r_sum += A[row][col];
// for column sum
c_sum += A[col][row];
if(row==col){
//for diagonal sum
d_sum += A[row][col];
}
}
//add row sum to new Array
N[row][SIZE] = r_sum;
//add column sum to Array
N[SIZE][row] = c_sum;
}
//add diagonal sum to New Array
N[SIZE][SIZE] = d_sum;
// Print New Array
printf("New Table Array ");
for(row=0; row<SIZE+1; row++)
{
for(col=0; col<SIZE+1; col++)
{
printf(" %d", N[row][col]);
}
printf(" ");
}
return 0;
}
/*
output
Enter elements in matrix of size 4x4:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 15
New Table Array
1 2 3 4 10
5 6 7 8 26
9 10 11 12 42
13 14 15 15 57
28 32 36 39 33
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.