166k views
3 votes
Consider the following switch statement where x is an int. If x is currently equal to 5, what will the value of x be after the switch statement executes? switch (x) { case 3 : x += 1; case 4 : x += 2; case 5 : x += 3; case 6 : x++; case 7 : x += 2; case 8 : x--; case 9 : x++

User Jfarrell
by
5.3k points

1 Answer

2 votes

Answer:

x=11

Explanation:

The switch case works like an if or if-else, where each of the cases are conditionals. Here we have 7 cases and we know that our variable begins with x=5.

First, it enters to case 5 because of x=5, so x+=3, this means we add 3 to the actual value of the variable ⇒ x=8.

At this point, if there's not break the program continues to the next case, executing the statements until a break or the end on the switch is reached.

In this order, the x = 8 and next we add 1 (case 6) ⇒ x=9. We add 2 (case 7) x+=2 ⇒ x=10. Then we rest 1 (case 8) ⇒ x=9 and then we add 1 again as in case 9 ⇒ x=11.

User Ozgur Ozturk
by
5.7k points