I dont understand this....

What i need is an explanation of why the code does what it does.
I dont understand why when i put in 3 it outputs an endless series of numbers meanwhile when i put in 6 it puts out 6842
Consider this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main() {
int n;
cin >> n;
 	while (n != 0) {
            cout << n << “ “ ;
             switch (n) {
                  case 4: n -= 3; break;
                  case 8: n /= 2; break;
                  case 1: n = 0; break;
                  default: n += 2; break;
}
};
      system(“pause”);
}

What will this program output if the user enters a 6?
What will this program output if the user enters a 3?
For 3, it will not match any cases and will hit the default, increasing to 5. Then, 5 will not match any cases and will hit the default, increasing to 7. All odd numbers (except 1) will hit the default, and just increase forever.

6, however, will hit the default the first time, but then will be 8 for the second loop. It will hit case 8, and be divided by 2, to become 4. 4 then has 3 subtracted from it, so it is 1. Finally, 1 matches with case 1, and n is 0, which ends the loop.
Topic archived. No new replies allowed.