I can't figure out what to do

solved
Last edited on
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
//Program Description
//     Displays the number of times
//     the numbers from 1 through 9 appear in a
//     two-dimensional array
//Revised by <your name> on <current date>

#include <iostream>

int main()
{
	const int numbers[5][3] = { {1, 2, 7}, // good idea to make it a const
                                {2, 5, 3}, // comma, not semicolon
                                {1, 9, 4},
                                {2, 6, 5},
                                {7, 2, 2}
                              };

	int counts[ /*9*/ 10 ] = {0} ; // braces are required. indices are 0, 1 ... 9
	                               // count[0] is unused; we use counts[1] to counts[9]

    // http://www.stroustrup.com/C++11FAQ.html#for
    // http://www.stroustrup.com/C++11FAQ.html#auto
	for( const auto& row : numbers ) // for each row in the 2D array
    {
        for( int v : row ) // for each number in the row
        {
            if( v > 0 && v < 10 ) // if it is a number in [1,9]
                ++counts[v] ; // increment the count
        }
    }

    // print out the counts of numbers 1 to 9
    for( int i = 1 ; i < 10 ; ++i )
        std::cout << "The number " << i << " appears " << counts[i] << " time(s).\n" ;
}

http://coliru.stacked-crooked.com/a/bc37db232a9f8af5
this was interesting but it didn't help. Thank you though
line 14 syntax error -- should end in comma not semicolon
line 19 syntax error -- int counts[9]{0} to initialize every index to 0.

Then I removed your cin.get() line near the end, and I finally got it to run:
The number 0 appears 0 time(s).
The number 1 appears 0 time(s).
The number 2 appears 0 time(s).
The number 3 appears 0 time(s).
The number 4 appears 0 time(s).
The number 5 appears 0 time(s).
The number 6 appears 0 time(s).
The number 7 appears 0 time(s).
The number 8 appears 0 time(s).


You should be more descriptive in what is wrong. JLBorges was just showing you that you don't need a triple loop -- a double nested loop is enough, and you should convert your code to not use three loops.

Edit: I see it.
counts[digit] = counts[digit]++;
This^ is logically wrong.
1. Your digit goes from 1 to 9, while your counts array only sets aside space for indices 0..8. So the first thing to change is to change that part to counts[digit-1].
2. You used post-increment operator. AFTER the assignment, the temporary (right of the equals sign) side gets incremented. You want either

1
2
3
4
5
6
7
counts[digit-1] = ++counts[digit-1];
//or
counts[digit-1] = counts[digit-1]+1;
//or
++counts[digit-1];
//or
counts[digit-1]++;


P.S. At the end, line 39, you want to display x+1, not x.
cout << "The number " << x+1 << " appears "
Last edited on
Thank you so much!
@nonya u can use map to get the results faster
Topic archived. No new replies allowed.