Muhammed bakijev
Muhammed bakijev

Reputation: 37

How do i output sum of rows of a 2D array C++

EDIT: I'm fairly new to c++. Began working with this language two weeks ago.

Sorry if this have been asked before, but i have searched everywhere on the web on how to sum individual rows in a 2D array and not found the answer that i was looking for.

i need to display the sum of each individual row in a[m][n], but for some reason this only works when my array is 2x2, but if it's 3x3 or bigger, then i get the following output in the terminal:

for intsance, a[3][3]= 
{1,2,3},   //this is determined by the user
{1,2,3},
{1,2,3};
 
then i get the following output:
9179942 //address of some sort???
6       // actual sum. code is working here (yay :D)
469090925// again something i dont understand

This is what i have so far

#include <iostream>
using namespace std;
int main(){
int m,n;
cout<<"Enter number of rows for array"<<endl;
cin>>m;
if (m>10){
    cout<<"More than 10 rows will be too big"<<endl;
    return 1;   
} 
cout<<"Enter number of columns for array"<<endl;
cin>>n;
if (n>10){
    cout<<"More than 10 columns will be too big"<<endl;
    return 1;
} 
int a[m][n];
for(int i=0; i<m;i++){
    cout<<"Enter "<<m<<" values into row "<<i+1<<endl;
    for(int j=0; j<n; j++){
        cout<<"a ["<<i<<"]["<<j<<"]: ";
        cin>>a[i][j];
    }
}
cout<<"Array dimensions: "<<m<<"x"<<n<<'\n'<<"resulting array: "<<endl;
for(int i=0; i<m;i++){
    for(int j=0; j<n; j++){
        cout<<a[i][j]<<"    ";
    }
    cout<<endl;
}
int avg[m];
int el_less_avg;
for(int i=0; i<m; i++){
    for(int j=0; j<n;j++){
        avg[i]+=a[i][j];
    }
}cout<<"\n\n";
for(int i=0; i<m; i++){
    
    cout<<avg[i]<<endl;
}

return 0;
}

Upvotes: 0

Views: 1159

Answers (2)

M.M
M.M

Reputation: 141658

int a[m][n]; is not allowed in Standard C++. The dimensions of C-style arrays must be known at compile-time. A program using this code could do literally anything.

You could replace this line with:

vector<vector<int>> a(m, vector<int>(n));

which seems like a mouthful at first, but you will find it makes your problem go away.

Another bonus of this approach is that you can then use range-based loops:

for(int x : avg)
    cout << x << endl;

which reduces the chance of making an error by using the wrong letter in the loop condition.

Upvotes: 1

kfsone
kfsone

Reputation: 24269

int avg[m];
int el_less_avg;
for(int i=0; i<m; i++){
    for(int j=0; j<n;j++){

You're not initializing these values so they're free to be whatever cruft is on the stack at the time. You need to initialize them.

int avg[m];
for (int i = 0; i < m; ++i) {
    avg[i] = 0;
    for (int j = 0; j < n; ++j) {
        avg[i] += a[i][j];
    }
}

Upvotes: 1

Related Questions