Class Exercise: Control Structure -- switch statement
Syntax:
switch (expression)
{
case value1:
statements1
[break;]
case value2:
statements2
[break;]
...
[default:
statements;
break; ]
}
1. Write a program fragment that includes a switch statement to test an
integer variable named choice, and when it is 1 assign the string value
"C++" to the string variable named language; when it is 2 assign "PHP" to
language; and when choice is some other value assign "unknown" to language.
print language.
2. Prepare a switch statement to test the case values referenced by the variable
named operator. When operator = '+', print the sum of operand1 plus operand2;
when '-', print difference between operand1 and operand2; when '*' print the
product of operand1 times operand2; when '/' and operand2 is not zero, print
quotient found by dividing operand1 by operand2 or print a zero-divide message;
and when there is no case value for the code tested, print an exception message.
[Create an html form to collect input values.]
3. Prepare a switch statement that falls through case labels for dayOfWeek (write
code for an int or a string test). When dayOfWeek is 1 ("Sunday) or 7
("Saturday") assign "weekend" to the string variable dayType; and when
dayOfWeek is 2 or 3 or 4 or 5 or 6 (for "Monday" ... "Friday"), assign
"weekday" to dayType.
4. Given that an int named score may range from 0 through 100, code a switch
statement to find a corresponding letter grade. The switch expression could
be score divided by 10. For a quotient of 9 or 10, assign 'A', for 8
assign 'B', 7 assign 'C', 6 assign 'D', when in the range of 0 through 5
assign 'F', otherwise assign '?'.