Sum of Diagonal Elements of Matrix in C++

C++ Program to print the sum of diagonal elements of a matrix. We’ll learn how to construct a C++ program to find the sum of a matrix’s diagonal elements in this programming example.

A square matrix has two diagonals, one on the left and one on the right. The row and column indexes of the left diagonal elements are equal, i==j, and the sum of the indices of the right diagonal elements is one less than the size of the matrix, i+j == size-1.

#include <iostream>
#define SIZE 10
using namespace std;
int main()
{
int matrix[SIZE][SIZE];
int left =0, right = 0;
cout << "Enter the elements in the matrix\n";
for(int i=0; i<SIZE ; i++){
for(int j=0; j<SIZE; j++){
cin >> matrix[i][j];
if(i==j)
left += matrix[i][j];
if((i+j) == SIZE-1)
right += matrix[i][j];
}
}
cout << "Sum of the left diagonal elements"<< left << endl;
cout << "Sum of the right diagonal elements "<< right << endl;
return 0;
}

 

Input:

4

1 2 3 4 4 3 2 1 7 8 9 6 6 5 4 3

Output:

Sum of the left Diagonal elements: 16

Sum of the right Diagonal elements: 20

What is diagonal matrix and its value

The main diagonal, also known as the leading diagonal, runs from the top left corner to the bottom right corner of a square matrix. Antidiagonal or counter diagonal is the other diagonal that runs from the top right to the bottom left corner. 

Lower triangular, upper triangular, and diagonal are all properties of a zero square matrix. Assuming it’s a square matrix. All items below the main diagonal in an upper triangular matrix are zero.

Namespace in C++ and why it is bad in program

A namespace is a declarative region that gives the identifiers within it a scope. Namespaces are used to arrange code into logical categories and to avoid name clashes, which might happen when you have many libraries in your codebase.

To contain this change, they built the std namespace. While this is acceptable for example code, importing the full std namespace into the global namespace is not recommended because it contradicts the purpose of namespaces and can result in name clashes.

What is #define in c and c++

The #define directive in the C programming language allows you to define macros within your source code. These macro definitions allow you to declare constant values that you can use throughout your code. Macro definitions aren’t variables, thus they can’t be altered by your computer code.

In the programming languages C and C++, sizeof is a unary operator. It calculates the number of char-sized units required to store an expression or a data type. The preprocessor macro CHAR BIT, defined in the standard include file limits, specifies the actual number of bits of type char. h.

Similar Programs