finding largest column in 2d array
For the array created I'm having a problem finding the largest column.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
#include<iostream>
using namespace std;
int main()
{
int a[3][4];
int i,j,s=0,sum=0;
srand(((unsigned)time(0)));
cout<<"Enter 9 elements of 3*4 Matrix \n";
for(i=0;i<3;i++)
for(j=0;j<4;j++)
a[i][j] = 1 + rand() % 10;
cout<<"Matrix Entered By you is \n";
for(i=0;i<3;i++)
{for(j=0;j<4;j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
for(i=0;i<3;i++)
{for(j=0;j<4;j++)
s=s+a[i][j];
cout<<"sum of"<<i+1<<" Row is"<<s;
s=0;
cout<<endl;
}
cout<<endl;
for(i=0;i<4;i++)
{for(j=0;j<3;j++)
s=s+a[j][i];
cout<<"sum of"<<i+1<<" Column is"<<s;
s=0;
cout<<endl;
}
cout<<endl;
for(i=0;i<3;i++)
for(j=0;j<4;j++)
sum=sum+a[i][j];
cout<<"Total Sum is "<<sum << endl;
int largestSum = 0;
for (int i = 0; i<3; i++)
{
int sum = 0;
for (int j = 0; j<4; j++)
{
sum += a[i][j];
}
if (sum > largestSum)
{
largestSum = sum;
}
}
cout << "largest row: " << largestSum << '\n';
int largestColumn = 0;
for (int i = 0; i<4; i++)
{
int sum = 0;
for (int j = 0; j<3; j++)
{
sum += a[j][j];
}
if (sum > largestColumn)
{
largestColumn = sum;
}
}
cout << "largest column: " << largestColumn << '\n';
}
|
hello, i understand your problem and the answer is simple but can be confusing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
int largestColumn = 0;
for (int i = 0; i<4; i++)
{
int sum = 0;
for (int j = 0; j<3; j++)
{
sum += a[j][i]; ///reverse i and j to count column wise
}
if (sum > largestColumn)
{
largestColumn = sum;
}
}
cout << "largest column: " << largestColumn << '\n';
}
|
Last edited on
Topic archived. No new replies allowed.