Fill in the C code missing in the main function such that the following three ta
ID: 3735460 • Letter: F
Question
Fill in the C code missing in the main function such that the following three tasks are performed.
a) Define a matrix A with dimensions NxN
b) Initialize the matrix A with values from 1 to NxN using two for loops.
c) Compute the sum of the elements on the diagonal (from the bottom-left to the top-right) in A using one for loop. The matrix A is required to follow the format shown below (N=3).
A = 1 2 3
4 5 6
7 8 9
#define N 10
int main(){
// a) Define the matrix A with dimensions NxN
// b) Initialize the elements in A
// c) Compute the sum of the elements on the diagonal of A.
int sum = 0;
printf(“The sum of the diagonal elements is %d ”, sum);
}
//end main
the code is supposed to return a value of 15
Explanation / Answer
#include <stdio.h>
#define N 10
int main(){
// a) Define the matrix A with dimensions NxN
int A[N][N],i,j,n;
printf("Enter the size of square matrix : ");
scanf("%d",&n);
printf(" Enter the elements of array : ");
// b) Initialize the elements in A
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&A[i][j]);
}
}
// c) Compute the sum of the elements on the diagonal of A.
int sum = 0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i==j)
sum = sum+A[i][j];
}
}
printf(" The sum of the diagonal elements is %d ", sum);
}
//end main
output:
Enter the size of square matrix :3
Enter the elements of array :
1 2 3
4 5 6
7 8 9
The sum of the diagonal elements is 15
Do ask if any query. Please upvote.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.