Gam*_*afa 1 c++ loops for-loop vector visual-studio
I want to find the sum of the diagonals of matrix that defined by user with this code , it works for main diagonal but not for secondary diagonal and i don't understand what the problem is. Any help would be appreciated.
#include <iostream>
using namespace std;
int main() {
int r, c, j,i,k,sum1,sum2;
cout << "Enter the size of matrix: ";
cin >> j;
int matrix[j][j];
for (r = 0; r < j; r++) {
for (c = 0; c < j; c++) {
cout << "matrix" << "[" << r << "]" << "[" << c << "] = ";
cin >> matrix[r][c];
}
}
cout << "\n";
for ( i = 0; i < j; i++) {
for ( k = 0; k < j; k++) {
cout << " "<<matrix[i][k] << " ";
}
cout << "\n";
}
cout<<"\n";
cout<<"Main diagonal is: ";
for( i=0;i<j;i++){
cout<<matrix[i][i];
}
cout<<"\n";
for( i=0;i<j;i++){
sum1=sum1+matrix[i][i];}
cout<<"Sum of the elements of main diagonal is: "<<sum1;
cout<<"\n";
cout<<"\n";
cout<<"Secondary diagonal is: ";
for(i=0,k=j-1;i<j;i++,k--){
cout<<matrix[i][k];
}
for(i=0,k=j-1;i<j;i++,k--){
sum2=sum2+matrix[i][k];
}
cout<<"Sum of the elements of secondary diagonal is: "<<sum2;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
For starters Variable Length Arrays is not a standard C++ feature. Use instead the class template std::vector.
For example
std::vector<std::vector<int>> matrix( j, std::vector<int>( j ) );
Run Code Online (Sandbox Code Playgroud)
Or at least allocate arrays dynamically as for example
int **matrix = new int *[j];
for ( i = 0; i < j; i++ ) matrix[i] = new int[j];
Run Code Online (Sandbox Code Playgroud)
In this case you should free all allocated memory before exiting the program as
for ( i = 0; i < j; i++ ) delete [] matrix[i];
delete [] matrix;
Run Code Online (Sandbox Code Playgroud)
Secondly neither sum1 nor sum2 were initialized.
int r, c, j,i,k,sum1,sum2;
Run Code Online (Sandbox Code Playgroud)
To calculate the sum of elements of the secondary diagonal you can write
sum2 = 0;
for ( i = 0; i < j; i++ ){
sum2 += matrix[i][j - i - 1];
}
Run Code Online (Sandbox Code Playgroud)