manual trace the following code int numbers [5][3] = { {1, 2, 5} , {2, 4, 3}, {1
ID: 3820595 • Letter: M
Question
manual trace the following code
int numbers [5][3] = { {1, 2, 5} , {2, 4, 3}, {1, 9, 8} , {2, 6, 5}, {7, 4, 2}};
int counts [9] = {0};
int digit = 1; //keeps track of numbers from 1 through 9
while (digit <= 9)
{
for (int row = 0; row < 5; row = row + 1)
for (int col = 0; col < 3; col = col + 1)
//count the number of times the digit appears in the numbers array
if (numbers[row] [col} == digit)
counts[digit - 1] = counts[digit - 1] + 1;
//end if
//end for
//end for
digit = digit + 1; //look for next digit
}//end while
//display counts
for (int x = 0; x < 9; x = x + 1)
cout << "The number " << x + 1 << " appears "
<< counts [x] << " time(s) ." << endl;
// end for
Explanation / Answer
digit=1
while ->true
checking each row and each column for equivalent of digit i.e. 1
as 1 has only 2 time in numbers array increase 2 to counts[1-1] i.e. counts[0]=2
digit=digit+1 => digit=2
while-> true
checking each row and each column for equivalent of digit i.e. 2
as 2 has only 4 times in numbers array increase 4 to counts[2-1] i.e. counts[1]=4
digit=digit+1 => digit=3
while-> true
checking each row and each column for equivalent of digit i.e. 3
as 3 has only 1 times in numbers array increase 1 to counts[3-1] i.e. counts[2]=1
digit=digit+1 => digit=4
while-> true
checking each row and each column for equivalent of digit i.e. 4
as 4 has only 2 times in numbers array increase 2 to counts[4-1] i.e. counts[3]=2
digit=digit+1 => digit=5
while-> true
checking each row and each column for equivalent of digit i.e. 5
as 5 has only 2 times in numbers array increase 2 to counts[5-1] i.e. counts[4]=2
digit=digit+1 => digit=6
while-> true
checking each row and each column for equivalent of digit i.e. 6
as 6 has only 1 times in numbers array increase 1 to counts[6-1] i.e. counts[5]=1
digit=digit+1 => digit=7
while-> true
checking each row and each column for equivalent of digit i.e. 7
as 7 has only 1 times in numbers array increase 1 to counts[7-1] i.e. counts[6]=1
digit=digit+1 => digit=8
while-> true
checking each row and each column for equivalent of digit i.e. 8
as 8 has only 1 times in numbers array increase 1 to counts[8-1] i.e. counts[7]=1
digit=digit+1 => digit=9
while-> true
checking each row and each column for equivalent of digit i.e. 9
as 9 has only 1 times in numbers array increase 1 to counts[9-1] i.e. counts[8]=1
digit=digit+1 => digit=10
while->false.
Display counts array i.e. [2,4,1,2,2,1,1,1,1]
i.e
The number 1 appears 2 times.
The number 2 appears 4 times.
The number 3 appears 1 times.
The number 4 appears 2 times.
The number 5 appears 2 times.
The number 6 appears 1 times.
The number 7 appears 1 times.
The number 8 appears 1 times.
The number 9 appears 1 times.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.