/*
Program for calculating sum of diagonals of a square matrix.
*/
#include<iostream>
using namespace std;
int main()
{
//variable declaration
int matrix[10][10], row, column, sumM=0, sumS=0, sum=0;
//For inputting size of matrix
cout << "Enter size of matrix:\n";
//for rows
do
{
cout << "Rows (Max-10)?\t";
cin >> row;
if (row > 10 || row < 0)
cout << "Invalid Input.....";
} while (row > 10 || row < 0);
//for columns
do
{
cout << "Columns (Max-10)?\t";
cin >> column;
if (column > 10 || column < 0 || column != row)
cout << "Invalid Input.....";
} while (column > 10 || column < 0 || column != row);
//For inputting matrix elements
cout << "Enter matrix elements:\n";
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
cout << "Index [" << i << "][" << j << "]?\t";
cin >> matrix[i][j];
}
}
//for calculating sum
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
if (i == j)
sumM += matrix[i][j];
if (i + j == row - 1)
sumS += matrix[i][j];
}
}
sum = sumS + sumM; //for total sum
//For formatting output
for (int i = 0; i < 40; i++)
cout << "==";
//For displaying entered matrix
cout << "Entered matrix is:\n\n";
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
cout << "\t" << matrix[i][j];
cout << endl;
}
//For formatting output
for (int i = 0; i < 40; i++)
cout << "==";
//For displaying SUM
cout << "\nSum of elements of Main diagonal is " << sumM;
cout << "\nSum of elements of Secondary diagonal is " << sumS;
cout << "\nSum of elements of both diagonals is " << sum;
cout << endl;
return 0;
}
OUTPUT
No comments:
Post a Comment