labeling and totaling 2d arrays

How do I add labels to rows and columns of a 2d array? How do I print a total at the end of each row and at the bottom of each column? This code is from Bucky's youtube video lesson 37 of C++. Could someone please make it so that the rows are Player 1 and Player 2 and the columns are Rounds 1-3 and then include the totals? Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;

int main()
{
    int bertha [2][3] = {{2,3,4},{7,8,9}}
    for (int row = 0; row < 2; row++)
    {
        for (int column = 0; column < 3; column++)
        {
            cout << bertha [row][column] << " ";
            
        }
            
    }

}
If you want to include the labels in the array, then the type must be changing to say string.

Aceix.
The basic idea would be something like this:
(probably contains things that you haven't learned yet; write your own code based on these leads)

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <iomanip>

int main()
{
    constexpr std::size_t NROWS = 2 ;
    constexpr std::size_t NCOLS = 3 ;
    const auto setw = std::setw(10) ; // feld width

    const int bertha [NROWS][NCOLS] = {{2,3,4},{7,8,9}} ;

    const char row_label_prefix[] = "Player" ;
    const char col_label_prefix[] = "Round" ;
    int row_total[NROWS] = {0} ;
    int col_total[NCOLS] = {0} ;

    // print col labels
    std::cout << setw << ' ' ;
    for( std::size_t column = 0; column < NCOLS ; ++column )
        std::cout << setw << col_label_prefix << column ;
    std::cout << setw << "total" << "\n\n" ;

    for( std::size_t row = 0; row < NROWS ; ++row )
    {
        // print row label
        std::cout << setw << row_label_prefix << row ;

        for( std::size_t column = 0; column < NCOLS ; ++column )
        {
            const int value = bertha [row][column] ;
            std::cout << setw << value << ' ' ;
            row_total[row] += value ;
            col_total[column] += value ;
        }

        // print the row total
        std::cout << setw << row_total[row] << '\n' ;
    }

    // print col totals
    std::cout << '\n' << setw << "total" ;
    for( std::size_t column = 0; column < NCOLS ; ++column )
        std::cout << std::setw(11) << col_total[column] ;
    std::cout << '\n' ;
}

http://coliru.stacked-crooked.com/a/d6e90eb85327033e
Topic archived. No new replies allowed.