Write a program that calculates the sum of elements of the first diagonal (right) in a square matrix.
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <conio.h>
#define SIZE 50
void main()
{
int A[SIZE][SIZE];
int R; /* dimensions */
int I, J; /* counters */
int sum;
do {
printf("Number of rows and columns of the square matrix (max.%d) : ", SIZE);
scanf("%d", &R);
} while (R <= 0 || R > SIZE);
for (I=0; I<R; I++)
for (J=0; J<R; J++)
{
printf("A[%d][%d] : ",I,J);
scanf("%d", &A[I][J]);
}
printf("\nMatrix :\n");
for (I=0; I<R; I++)
{
for (J=0; J<R; J++)
printf("%7d", A[I][J]);
printf("\n");
}
sum=0;
for (I=0; I<R; I++)
for (J=0; J<R; J++)
if(I==J)
sum+=A[I][J];
printf("The sum of the main diagonal is equal to %d.\n", sum);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Probability density of the p-pulse for a particle