Here's a C Program with output and explanation to find sum of diagonal elements of the given matrix using Nested Loops and For Loops.
# include <stdio.h> # include <conio.h> void main() { int mat[10][10] ; int i, j, size, sum = 0 ; clrscr() ; printf("Enter size of the square matrix : ") ; scanf("%d", &size) ; printf("\nEnter the elements of the matrix : \n\n") ; for(i = 0 ; i < size ; i++) for(j = 0 ; j < size ; j++) scanf("%d", &mat[i][j]) ; for(i = 0 ; i < size ; i++) sum = sum + mat[i][i] ; printf("\nThe sum of diagonal elements in the matrix is : %d", sum) ; getch() ; }
Output of the above program -
Enter size of the square matrix : 3
Enter the elements of the matrix :
1 2 3
4 5 6
7 8 9
The sum of diagonal elements in the matrix is : 15
Explanation of above program -
In this program, we have a square matrix mat of maximum size 10 x 10. The variable size holds the value of size of matrix and the variable sum contains the sum of diagonal elements of the matrix mat.
Now, first we ask the user to enter the size of the matrix and store the inputted value in the variable size. Next using a nested for loop we enter the values in the matrix mat.
Fact: In a square matrix, diagonal elements are those elements that have same row and column number. E.g. mat[1][1], mat[2][2], mat[3][3] etc.Now using the next for loop we calculate the sum of all the diagonal elements of the matrix mat by adding simply those elements for which the row and column numbers are same.
Hello There,
Thanks for highlighting this and indicating about
C Program to Find Sum of Diagonal Elements of Matrix where more study and thought is necessary.
I started to program with C and have some programming in JAVA. However, I have a small understanding problem with the following simple code below.
I understand that at the command "while (isspace(ch=getc(in)))" the programm reads till if founds a character that is either a " or a blank. This symbol is assigned to the variable delim.
Is it then correct to say that the program starts again at the same position as before and continues to read the string till "((ch=getc(in))!=delim)" is fulfilled?
THANK YOU!! This saved my butt today, I’m immensely grateful.
Gracias,
Sanvi