Here is the code with spaces after the cases, indented to reflect the block structure, and with the code needed to make it a program:
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
|
#include <iostream>
using namespace std;
int
main()
{
int x, value;
int a = 0, b = 0, c = 0, d = 0;
for (x = 10240953; x != 0; x = x / 10) {
value = x % 10;
switch (value) {
case 2:
case 4:
case 6:
case 8:
a++;
break;
case 3:
case 5:
b++;
case 9:
case 7:
c++;
break;
default:
d++;
break;
}
}
cout << "a" << a << "b" << b << "c" << c << "d" << d;
}
|
The first thing to do is recognize that the loop on lines 10 & 11 causes value to take on the value of each digit in 10240953, in reverse order. So it's 3, then 5, then 9, 0, 4, 2, 0, and finally 1.
Next write the letters a,b,c,d on a sheet of paper, one per line:
Now simply examine the switch statement for each of those digits values and put a check mark next to a letter each time it's variable gets incremented.
For example, the first time through the loop, value=3. Control transfers to line 22 where b gets incremented. Then it falls through to line 25 and increments a. Then it breaks out of the switch statement. So your paper now looks like this:
Continue the same way with the rest of the digits. When you're done, your sheet will show how many times each variable got incremented. Easy peasy.