In: Computer Science
21. What is the output of the following segment of code if 7 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 7: total = total + 3; case 8: total = total + 6; default: total = total + 4; } cout << total << endl;
The output of the given segment of code when 7 is entered as the input by the user is 13.
Switch
statement:
A switch statement allows us to select an option out of several
options present based on the choice.
Syntax:
switch(choice/expression)
{
case value1: block-1; break;
case value2: block-2; break;
.
.
//Any number of case statements is allowed.
default: block-d;
}
The choice can either be an integer value, character or an
expression which evaluates to an integer value. Based on this
value, the control is transferred to particular case value. If the
value of the choice does not match any of the case values, then the
statements in the default block will be executed, if default case
is not specified then control comes out of the switch
statement.
During execution, if the break statement is executed, then the
control comes out of the switch statement and the statements after
the switch statement is executed. If there is no break statement
then the next cases are executed until a break is encountered or
till the end of switch case block.
Given code
explanation:
int num; // variable declaration
int total = 0; // variable declaration and
initialization
cout << "Enter a number from 1 to 10: ";
cin >> num; // read the number from user
switch (num) // Based on the entered number execute the switch case
statements
{
// case-1 and case-2 have common statement to execute which is
storing the value 5 in total.
case 1:
case 2: total = 5;
case 3: total = 10; // storing the value 10 in total.
case 7: total = total + 3; // add 3 to the total
case 8: total = total + 6; // add 6 to the total
default: total = total + 4; //add 4 to the total
}
cout << total << endl; // print the total
Note: There is no break statement after the cases, so all the cases are executed following the case which is entered as choice.
When the number entered is 7, then the control goes to the case
7 and executes its statement, since there is no break after case 7,
all the following cases are executed.
So, after executing case-7,
total=total+3=0+3=3(initially total=0), next
case-8 is executed,
total=total+6=3+6=9(new total value obtained from
case-7 is 3), finally
default case is executed,
total=total+4=9+4=13(new total value
obtained from case-8 is 9), come out of the switch block and
execute the following statement which is printing the total, so it
prints 13 as output.