Search code examples
c++arraysmultidimensional-arrayrevision

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;
}

Solution

  • 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];
        }
    }