Reputation: 154
I tried to get the sum of the rows and columns of a two dimensional array, but the result is 0. I don't know what my mistake is. Thank you for you help.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int characters[50][50],rc,sum=0,horizontal[10]={0},vertical[10]={0},c,r;
cout<<"Please enter integer : ";
cin>>rc;
cout <<" The matrix is : \n";
for(r=0;r<rc;r++){
for( c=0;c<rc;c++){
sum=sum+1;
characters[r][c]=sum;
cout<<characters[r][c]<< " ";
horizontal[r]=horizontal[r]+characters[r][c];
vertical[c]=vertical[c]+characters[c][r];
}
cout<< "The sum of horizontal is = " <<horizontal[r]<<" and The sum of vertical is "<<vertical[c];;
cout<<endl;
}
return 0;
}
This is the result of this code
Please enter integer : 3
The matrix is :
1 2 3 The sum of horizontal is = 6 and The sum of vertical is 0
4 5 6 The sum of horizontal is = 15 and The sum of vertical is 0
7 8 9 The sum of horizontal is = 24 and The sum of vertical is 0
Upvotes: 0
Views: 451
Reputation: 489
You can't compute sum of vertical before fill the matrix.
vertical[c] = vertical[c] + characters[c][r]
is wrong.
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
int characters[50][50],rc,sum=0,horizontal[10]={0},vertical[10]={0},c,r;
cout<<"Please enter integer : ";
cin>>rc;
cout <<" The matrix is : \n";
for(r=0;r<rc;r++){
for( c=0;c<rc;c++){
sum=sum+1;
characters[r][c]=sum;
cout<<characters[r][c]<< " ";
}
cout << endl;
}
for(r=0;r<rc;r++){
for( c=0;c<rc;c++){
horizontal[r]=horizontal[r]+characters[r][c];
vertical[r] = vertical[r] + characters[c][r];
}
cout<< "The sum of horizontal is = " <<horizontal[r]<<" and The sum of vertical is "<<vertical[r];
cout<<endl;
}
return 0;
}
Upvotes: 1