Sum of Diagonal Elements of Matrix in C Language
Program Description:
write a Program to calculate the Sum of Diagonal Elements of Matrix in C Programming Language. The program should accept a matrix from the user and calculate the sum of the main diagonal elements of the array.
Diagonal Elements in Matrix:
We have a matrix X with dimensions m x n. Where each element is xij, Then X[i][j] is a diagonal element if i == j
Let’s look at an example.
Matrix X:
1 2 3 |
100 200 300 400 500 600 700 800 900 |
The diagonal Elements of the Matrix X are:
100 500 900
The Sum of the diagonal elements is 1500
Here is the graphical representation of the Diagonal elements of a Matrix
Prerequisites:
- Multi-Dimensional Arrays in C
- Read and Print 2D Arrays in C
- Passing 2D Arrays to Functions
- One dimensional Arrays in C
Let’s look at a C Program to calculate the Sum of Diagonal Elements of a Matrix.
Sum of Diagonal Elements of Matrix in C Program Explanation:
- Create two integer constants named ROWS and COLUMNS, Which holds the max number of rows and columns.(Change this number if you want to use large arrays)
- Start the Program by declaring a Matrix (2D Arrays) named X[ROWS][COLUMNS]. The row size and column size of the matrices are ROWS and COLUMNS respectively.
- Prompt the user to provide the desired Row size and Column Size, and update them in the variables rows and columns respectively.
- Check if the array size is going out of present limits ( 1-100) using the (rows >= ROWS || rows <= 0 || columns >= COLUMNS || columns <= 0) condition, And display an error message if the row/column sizeis beyond the limits.
- Take the user input for Matrix-X, We need to create two For Loops, One For Loop will iterate over the rows, and the Second For Loop will iterate over the columns
- Create the First For Loop ( Outer Loop), Start the iteration from i=0, and go till the i<rows (which is equal to for(i=0; i<rows; i++) ). At Each iteration of the Outer Loop,
- Create the second For Loop ( Inner Loop). This loop is a Nested loop that will be inside the Outer Loop. Start the Loop from j=0 and go till the j<columns (i.e for(j=0; j<columns; j++) ). At each iteration of the Inner Loop
- Prompt the user to provide the Matrix or 2D Array element and Read the element using the scanf function and Update the X[i][j] element.
- Repeat the above step for all elements in the 2D array or matrix
- Create the second For Loop ( Inner Loop). This loop is a Nested loop that will be inside the Outer Loop. Start the Loop from j=0 and go till the j<columns (i.e for(j=0; j<columns; j++) ). At each iteration of the Inner Loop
- Initialize the variable sum to hold the sum of diagonal elements. initialize sum with zero(0)
- To Calculate the Sum of Diagonal Elements of the Matrix-X, We need to go through the array and print all elements where the element row index is equal to the column index. So create another two loops to iterate over the matrix.
- Create Outer For Loop to iterate over rows – for(i=0; i<rows; i++)
- Create Inner For loop to iterate over columns – for(j=0; j<columns; j++), At Each Iteration,
- Add the X[i][j] to sum where i == j.
- Create Inner For loop to iterate over columns – for(j=0; j<columns; j++), At Each Iteration,
- Once the above Step-9 is finished, The sum variable contains the sum of the diagonal elements of the matrix. And display the results on the console.
Program to Sum of Diagonal Elements of Matrix in C language:
Here is the program to calculate the sum of Diagonal Elements of the matrix in C Programming language
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
/* Program to Calculate sum of diagnoal elements of the matrix SillyCodes.com */ #include <stdio.h> // Define MAX ROWS and COLUMNS const int ROWS=100; const int COLUMNS=100; int main() { // Declare two matrices. // 'X' is Input matrice int X[ROWS][COLUMNS]; int rows, columns, i, j; // Take the Row size and Column size from user printf("Enter the Row size for Matrix(1-%d): ", ROWS); scanf("%d", &rows); printf("Enter the Column Size for Matrix(1-%d): ", COLUMNS); scanf("%d", &columns); // check for array bounds if(rows >= ROWS || rows <= 0 || columns >= COLUMNS || columns <= 0) { printf("Invalid Rows or Columns size, Please Try again \n"); return 0; } // Take the user input for 1st Matrix - 'X' printf("Enter Elements for the Matrix(X) of Size %dX%d: \n", rows, columns); for(i=0; i<rows; i++) { for(j=0; j<columns; j++) { // printf("X[%d][%d]: ", i, j); scanf("%d", &X[i][j]); } } // Initialize the 'sum' with Zero int sum = 0; // Calculate the sum of diagonal elements // Iterate over the rows and columns for(i=0; i<rows; i++) { for(j=0; j<columns; j++) { if(i == j) { // Diagnoal Element, Add to 'sum' sum = sum + X[i][j]; } } } // Print the sum of Diagonal Elements of the Matrix printf("The Sum of Diagonal Elements of the Matrix X is : %d\n", sum); return 0; } |
Program Output:
Compile and Run the program
1 2 3 4 5 6 7 8 9 10 |
$ gcc sum-of-diagonal.c $ ./a.out Enter the Row size for Matrix(1-100): 3 Enter the Column Size for Matrix(1-100): 3 Enter Elements for the Matrix(X) of Size 3X3: 100 200 300 400 500 600 700 800 900 The Sum of Diagonal Elements of the Matrix X is : 1500 $ |
In the above program, The Sum of the main diagonal elements is 1500 (i.e 100, 500, and 900)
Let’s look at a few more examples.
1 2 3 4 5 6 7 8 9 10 |
$ ./a.out Enter the Row size for Matrix(1-100): 4 Enter the Column Size for Matrix(1-100): 4 Enter Elements for the Matrix(X) of Size 4X4: 1 3 7 8 9 8 2 3 8 7 3 0 8 4 5 8 The Sum of Diagonal Elements of the Matrix X is : 20 $ |
As excepted the program is displaying the desired results.
1 2 3 4 5 |
$ ./a.out Enter the Row size for Matrix(1-100): 500 Enter the Column Size for Matrix(1-100): 600 Invalid Rows or Columns size, Please Try again $ |
If the user enters an Invalid size, Program displays an error message Invalid Rows or Columns size, Please Try again
Sum of Diagonal Elements of Matrix using user defined Functions in C:
Here is the modified version of the sum of diagonal elements of matrix program using the user defined functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
/* Program to Calculate the sum of Diagonal Elements of Matrix in C using FUnctions SillyCodes.com */ #include <stdio.h> // Define MAX ROWS and COLUMNS const int ROWS=100; const int COLUMNS=100; /** * @brief - Read Matrix from the user and update 'X' * * @param rows - Rows in Matrix(2Darray) * @param columns - Columns in 'X' * @param X[][] - 'X' is Matrix or 2D array */ void readMatrix(int rows, int columns, int X[rows][columns]) { int i, j; for(i=0; i<rows; i++) { for(j=0; j<columns; j++) { //printf("X[%d][%d]: ", i, j); scanf("%d", &X[i][j]); } } } /** * @brief - Print the diagonal elements of the Matrix * * @param rows - Rows in Matrix(2Darray) * @param columns - Columns in 'X' * @param X[][] - 'X' is a Matrix or 2D array * @return int - sum of diagonal elements of the matrix */ int sumOfDiagonal(int rows, int columns, int X[rows][columns]) { int i, j, sum = 0; for(i=0; i<rows; i++) { for(j=0; j<columns; j++) { if(i == j) { // Diagnoal Element, Add to 'sum' sum = sum + X[i][j]; } } } // return sum of diagonal elements return sum; } int main() { // Declare two matrices. // 'X' is Input matrice int X[ROWS][COLUMNS]; int rows, columns, i, j; // Take the Row size and Column size from user printf("Enter the Row size for Matrix(1-%d): ", ROWS); scanf("%d", &rows); printf("Enter the Column Size for Matrix(1-%d): ", COLUMNS); scanf("%d", &columns); // check for array bounds if(rows >= ROWS || rows <= 0 || columns >= COLUMNS || columns <= 0) { printf("Invalid Rows or Columns size, Please Try again \n"); return 0; } // Take the user input for 1st Matrix - 'X' printf("Enter Elements for the Matrix(X) of Size %dX%d: \n", rows, columns); readMatrix(rows, columns, X); // Calculate the sum of the Diagonal Elements of the Matrix printf("The Sum of Diagonal Elements of the Matrix X is : %d\n", sumOfDiagonal(rows, columns, X)); return 0; } |
We have created two user defined functions(Except main() function) in the above program
- readMatrix() function is used to read the elements from the user and update the given matrix.
- The sumOfDiagonal() function will calculate the sum of the main diagonal elements and returns the results.
Program Output:
Let’s compile and run the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
$ gcc sum-of-diagonal.c $ ./a.out Enter the Row size for Matrix(1-100): 4 Enter the Column Size for Matrix(1-100): 4 Enter Elements for the Matrix(X) of Size 4X4: 1 9 8 3 9 2 3 9 7 4 8 5 8 1 3 4 The Sum of Diagonal Elements of the Matrix X is : 15 $ ./a.out Enter the Row size for Matrix(1-100): 2 Enter the Column Size for Matrix(1-100): 2 Enter Elements for the Matrix(X) of Size 2X2: 8 2 1 2 The Sum of Diagonal Elements of the Matrix X is : 10 $ ./a.out Enter the Row size for Matrix(1-100): 500 Enter the Column Size for Matrix(1-100): 000 Invalid Rows or Columns size, Please Try again $ |
As we can see from the above output, The program is excepted results.
Related Matrix Programs:
- C Program to Read and Print Matrix or 2D Array
- C Program to demonstrate How to Pass 2D Array to Functions
- C Program to Multiplication of two Matrices
- C Program to Add Two Matrices
- C Program to Subtract Two Matrices
- C Program to Calculate the Transpose of Matrix
- C Program to Check Two Matrices are Equal
- C Program to Check Multiplicability of Two Matrices
- C Program to Check a Sparse Matrix
- Matrix and Scaler Multiplication Program in C
1 Response
[…] Sum of Diagonal Elements of Matrix in C Language […]