Home > Back-end >  2D array to find sum of columns, doesn't display properly
2D array to find sum of columns, doesn't display properly

Time:03-31

#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?

CodePudding user response:

Remove the arguments from table. It does not make sense to pass i and j as pointers (int i[] is just a obfuscated way of a int* i argument) and then not use them in the function. Instead you should pass a pointer to the array rather than using a global variable. Though one thing at a time...

If you want a header to appear before the rest of the output, then you need to print a header before the rest of the output:

void table() {
    std::cout << "column\tsum\n";
    for (int k = 0; k < 5; k  ) {
        int sum = 0;
        for (int l = 0; l < 4; l  ) {
            sum  = m[l][k];
        }
        cout << k << "\t" << sum << '\n';
    }
}

CodePudding user response:

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
  • Related