C++ program to find the sum of diagonals of a matrix.
#include<iostream>
#include<conio.h>
#include<vector>
using namespace std;
std::vector<vector<int>> matrix;
int r;
int getarray()
{
cout<<"Enter the number of rows and colums of array : ";
cin>>r;
for (int i = 0; i < r; i++)
{
std::vector<int> row;
for (int j = 0; j < r; j++)
{
int value;
std::cout <<"enter row "<<i+1<<" element "<<j+1<<endl;
std::cin >>value;
row.push_back(value);
}
matrix.push_back(row);
}
return 0;
}
int showarray()
{
for (int i = 0; i < r; i++) {
for (int j = 0; j < r; j++) {
std::cout <<matrix[i][j]<<'\t';
}
std::cout << '\n';
}
return 0;
}
int diagsum()
{
int sum1=0,sum2=0;
for(int i=0;i<r;i++)
{
sum1+=matrix[i][i];
sum2+=matrix[i][(r-1)-i];
}
std::cout<<"\n\nSum of 1st diagonal : "<<sum1;
std::cout<<"\nSum of 2nd diagonal : "<<sum2;
return 0;
}
int main()
{
std::cout << "Enter the array :" << '\n';
getarray();
std::cout << "\n\nThe array is :\n\n" << '\n';
showarray();
diagsum();
getch();
return 0;
}
No comments:
Post a Comment