Programming in C

(Barry) #1

86 Chapter 6 Making Decisions


break;
case '-':
printf ("%.2f\n", value1 - value2);
break;
case '*':
printf ("%.2f\n", value1 * value2);
break;
case '/':
if ( value2 == 0 )
printf ("Division by zero.\n");
else
printf ("%.2f\n", value1 / value2);
break;
default:
printf ("Unknown operator.\n");
break;
}

return 0;
}

Program 6.9 Output
Type in your expression.
178.99 - 326.8
-147.81

After the expression has been read in, the value of operatoris successively compared
against the values as specified by each case.When a match is found, the statements con-
tained inside the case are executed.The breakstatement then sends execution out of the
switchstatement, where execution of the program is complete. If none of the cases
match the value of operator,the defaultcase, which displays Unknown operator.is
executed.
The breakstatement in the defaultcase is actually unnecessary in the preceding
program because no statements follow this case inside the switch.Nevertheless, it is a
good programming habit to remember to include the breakat the end of every case.
When writing a switchstatement, bear in mind that no two case values can be the
same. However, you can associate more than one case value with a particular set of
program statements.This is done simply by listing the multiple case values (with the
keyword casebefore the value and the colon after the value in each case) before the
common statements that are to be executed. As an example, in the following switch
statement, the printfstatement, which multiples value1by value2, is executed if
operatoris equal to an asterisk or to the lowercase letter x.

Program 6.9 Continued
Free download pdf