Search code examples
c++loopsfor-loopmultidimensional-arrayfunction-definition

2D array to find sum of columns, doesn't display properly


#include <iostream>
#include <iomanip>
using namespace std;

void table(int i[], int j[]);
int m[4][5] = {
{2,5,4,7},
{3,1,2,9},
{4,6,3,0},
};


int main()
{
    table({}, {});
}


void table(int i[], int j[]) {
    for (int k = 0; k < 5; k++) {
        int sum = 0;
        for (int l = 0; l < 4; l++) {
            sum += m[l][k];
        }
        cout << "column: " << " " << sum << '\n';
    }
}

Basically I want it to display like this:

Column      Sum of Column Entries
1               9
2               12
3               9
4               16

and I'm not sure how to go about doing this. Do I write a loop?


Solution

  • The presented code does not make a sense.

    For starters the parameters of the function table are not used. Moreover they are initialized as null pointers after this call

    table({}, {});
    

    Also the array m is declared with 4 rows and 5 columns. It means that the last row contains all zeroes and the last column also contains zeroes.

    It seems you mean an array with three rows and four columns.

    The program can look the following way

    #include <iostream>
    $include <iomanip>
    
    const size_t COLS = 4;
    
    void table( const int a[][COLS], size_t rows );
    
    int main()
    {
        int m[][COLS] = 
        {
            { 2, 5, 4, 7 },
            { 3, 1, 2, 9 },
            { 4, 6, 3, 0 },
        };
    
        table( m, sizeof( m ) / sizeof( *m ) );
    }
    
    
    void table( const int a[][COLS], size_t rows )
    {
        std::cout << "Column     Sum of Column Entries\n";
    
        for (size_t j = 0; j < COLS; j++)
        {
            int sum = 0;
            for (size_t i = 0; i < rows; i++)
            {
                sum += a[i][j];
            }
            std::cout << j + 1 << ":" << std::setw( 14 ) << ' ' << sum << '\n';
        }
        std::cout << '\n';
    }
    

    The program output is

    Column     Sum of Column Entries
    1:              9
    2:              12
    3:              9
    4:              16