164k views
0 votes
What is the output of the following segment of code if the value 4 is input by the user when asked to enter a number?

int num;
int total = 0;
cout << "Enter a number from 1 to 10: ";
cin >> num;
switch (num){
case 1:
case 2: total = 5;
case 3: total = 10;
case 4: total = total + 3;
case 8: total = total + 6;
default: total = total + 4;
}
cout << total << endl;

A. 13
B. 6
C. 10
D. 17

1 Answer

4 votes

Final answer:

The output of the code when the input is 4 is 13 because the switch statement falls through cases 4, 8, and the default case, adding up to a total of 13.

Step-by-step explanation:

The output of the given code segment when the user inputs the value 4 is calculated through a switch statement. Since there are no break statements, the execution falls through each case after matching the case with value 4, meaning that total is first added by 3 in case 4, then by 6 in case 8, and finally by another 4 in the default case. Therefore, the calculation will be total = 0 + 3 + 6 + 4, which gives us a total of 13.

User Cody Brimhall
by
8.5k points