Programming in C

(Barry) #1
The ifStatement 83

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

return 0;
}


Program 6.8A Output


Type in your expression.
123.5 + 59.3
182.80


Program 6.8A Output (Rerun)


Type in your expression.
198.7 / 0
Division by zero.


Program 6.8A Output (Second Rerun)


Type in your expression.
125 $ 28
Unknown operator.


When the operator that is typed in is the slash, for division, another test is made to
determine if value2is 0. If it is, an appropriate message is displayed at the terminal.
Otherwise, the division operation is carried out and the results are displayed. Pay careful
attention to the nesting of the ifstatements and the associated elseclauses in this case.
The elseclause at the end of the program catches any “fall throughs.”Therefore, any
val ue of operatorthat does not match any of the four characters tested causes this else
clause to be executed, resulting in the display of “Unknown operator.”


Program 6.8A Continued
Free download pdf