Adding rows and columns in a 2d array

Hi all, I have been working on this problem for quite some time now, and can't seem to find the errors in my code. The problem is: Write a program to total each individual row and each individual column of a 2d array consisting of 10 rows and 6 columns using a single nested loop to accomplish this task. Use a random number generator to store integers in the range of 1 to 10 in the array

I haven't gotten to the random number generator part yet, as I would like to get down the adding rows and columns down first. I am getting some errors when adding rows and columns. Thanks!

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
  #include <iostream>
#include <iomanip>

using namespace std;
int main(void) {

	const int ROWS = 10, COLUMNS = 6;

	int table[ROWS][COLUMNS] = { { 1,2,3,4,5,6 } , {2 }, {3}, {4}, {5}, {6}, {7}, {8}, {9}, {10} };
	int rowSum, colSum;

	for (int i = 0; i < ROWS; i++) {

		for (int j = 0; j < COLUMNS; j++) {
			rowSum += table[i][j];
			colSum += table[j][i];
		}

		cout << "the sum of row " << i + 1 << " is " << rowSum << endl;
		cout << "the sum of col " << i + 1 << " is " << colSum << endl;

	}
	

	return 0;
}
When asked to do two things at once, it is often useful to first program them individually. After that you can see where the two routines share commonality.

tl;dr
Write a program to total only the rows.
Then write a program to total only the columns.
Compare and contrast the two programs.


BTW, to create your table, structure it like this:

9
10
11
12
13
int table[ROWS][COLUMNS] =
{
  { 1,2,3,4,5,6 },

};

Now just select the entire line (line 11) and copy it nine times. ;^)

Good luck!
First thing: names have power. Different names do not solve any issue, but they might help to see the issues:
1
2
3
4
5
6
for ( int row = 0; row < ROWS; row++ ) {
  for ( int col = 0; col < COLUMNS; col++ ) {
    rowSum += table[ row ][ col ];
    colSum += table[ col ][ row ]; // Does the table have ROWS columns?
  }
}


1
2
3
4
5
int rowSum; // uninitialized, unknown value
rowSum += 7; // unknown+7 is still unknown

int colSum {0}; // initialized with known value
colSum += 42; // 0+42 == 42 

The rowSum should be 0 before the first element of a row. You keep adding to same sum from all rows.

You cannot know the sum of a column before you have added elements from every row. That means after the loop, on line 23.
You have COLUMNS columns. You cannot store all sums in one int. You need an array.

You can use loops to show the sums. It is the calculation that is limited to two nested loops.
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
#include <iostream>
#include <iomanip>
#include <string>
#include <valarray>
using namespace std;

int main()
{
   const int ROWS = 10, COLS = 6;
   valarray< valarray<int> > V( valarray<int>( COLS ), ROWS);
   valarray<int> colSum( 0, COLS );

   for ( int i = 0; i < ROWS; i++ )
   {
      for ( int j = 0; j < COLS; j++ ) V[i][j] = COLS * i + j;
   }

   for ( auto &row : V )
   {
      for ( auto e : row ) cout << setw(5) << e << ' ';
      cout << "| " << row.sum() << '\n';
      colSum += row;
   }

   cout << string( COLS * 6, '-' ) << '\n';
   for ( auto e : colSum ) cout << setw(5) << e << ' ';
   cout << '\n';
}


    0     1     2     3     4     5 | 15
    6     7     8     9    10    11 | 51
   12    13    14    15    16    17 | 87
   18    19    20    21    22    23 | 123
   24    25    26    27    28    29 | 159
   30    31    32    33    34    35 | 195
   36    37    38    39    40    41 | 231
   42    43    44    45    46    47 | 267
   48    49    50    51    52    53 | 303
   54    55    56    57    58    59 | 339
------------------------------------
  270   280   290   300   310   320  


I'm slightly surprised that colSum = V.sum(); doesn't seem to produce anything, given that line 22 works as expected.



For the random one then, well, just playing ...
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
#include <iostream>
#include <iomanip>
#include <string>
#include <valarray>
#include <numeric>
#include <ctime>
#include <cstdlib>
using namespace std;

ostream & operator << ( ostream & strm, const valarray<int> V )
{
   for ( auto e : V ) strm << setw(5) << e << ' ';
   return strm;
}
    

int main()
{
   const int ROWS = 10, COLS = 6;
   valarray< valarray<int> > V( valarray<int>( COLS ), ROWS);
   srand( time( 0 ) );

   for ( auto &row : V )
   {
      row = row.apply( []( int i ) { return 1 + rand() % 10; } );
      cout << row << "| " << row.sum() << '\n';
   }
   
   cout << string( COLS * 6, '-' ) << '\n';
   cout << accumulate( begin( V ), end( V ), valarray<int>( 0, COLS ) ) << '\n';
}


    2     6     6     9    10     6 | 39
    9     2     1     4     6     3 | 25
    3     2     1     6     5     9 | 26
    1     5     5     5     4    10 | 30
    3     6     2     5     2     8 | 26
    4     2     1    10     4     5 | 26
    2     8     6     3     1    10 | 30
    4     4     4     8     8     5 | 33
    3     1     3     7     6     6 | 26
    6     7     9     9     5     4 | 40
------------------------------------
   37    43    38    66    51    66 
Last edited on
@lastchance
most of the code you putted there is new to me , what is ostream I know it stands for outputStream but you rreturned a value and that means its a printer?
at line 23 what did you do ?
auto & row : v.
that's some advanced c++ skills . :D
I could write it in a different way and I was about to but what you did there attracted me , could you please explain what you did?
ostream is ANY output stream. I was defining the operation << for a particular numerical array type called a valarray. The operation returns a reference to a stream so that multiple outputs can be chained together in a single statement. It is defined purely for convenience here.

auto is used where the compiler can identify the type itself and avoids having to explicitly write out a complicated type. If you have used Python you will know that that language can assign appropriate types without you being explicit about it: this is the nearest that c++ has to offer. The & is used (here) as a "reference" or "view" on the variable to avoid an expensive copy of the potentially large array row. It's used for a lot of other things as well, which is potentially confusing.

I used a valarray because it has useful little member functions like sum(), apply() and whole-array operations that are built into many other languages and I regard as "natural". It is good for numerical arrays. Some compilers (notably Intel) provide considerable optimisation for it.

There is nothing here that couldn't be done with a standard array, however. It's just that would take more lines of code and explicit loops.
Last edited on
The for ( A b : c ) { } is range-based for-loop syntax that appeared with C++11.
See https://en.cppreference.com/w/cpp/language/range-for


The auto is a placeholder type that was also added by C++11.
See https://en.cppreference.com/w/cpp/language/auto

Older, pre-C++11 language had keyword auto too, but it was something entirely different.
See https://en.cppreference.com/w/cpp/language/storage_duration
Topic archived. No new replies allowed.