C Program to Calculate Sum of Non-diagonal Elements in a Matrix

Write a program to calculate sum of non-diagonal elements in a matrix in C/C++.

For example,

Input
1 2 2
0 3 0
1 1 1
Output
Sum of non-diagonal elements: 6

Before we go any further, we need to understand what a non-diagonal element is. An element of a square matrix is a non-diagonal element if the row number is not equal to the column number.

In the program given below, we are traversing each element of the matrix and checking if the element is diagonal or non-diagonal. If the element is non-diagonal, we add it to the final sum.

#include <stdio.h>

// function to get the sum of non-diagonal element
// n: order of matrkx
// matrix[][]: matrix of order n
int sum_non_diagonal(int n, int matrix[][50]) {

	int sum = 0;
	for (int i = 0; i < n; ++i) {
		for (int j = 0; j < n; ++j) {
			// if i != j, then it implies that
			// matrix[i][j] is a non-diagonal elements
			// thus, we add it to the final sum
			if (i != j) {
				sum += matrix[i][j];
			}
		}
	}
	return sum;
}

int main() {

	int n;
	int matrix[50][50];

	printf("Enter Order of Matrix: ");
	scanf("%d", &n);

	printf("Enter Matrix Elements:\n");
	for (int i = 0; i < n; ++i) {
		for (int j = 0; j < n; ++j) {
			scanf("%d", &matrix[i][j]);
		}
	}

	printf("Sum of non-diagonal elements: %d", sum_non_diagonal(n, matrix));

}

Output

Enter Order of Matrix: 3
Enter Matrix Elements:
0 1 1
1 1 1
3 0 1
Sum of non-diagonal elements: 7

Read

Leave a Comment

Your email address will not be published. Required fields are marked *