20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The if Statement<br />

83<br />

Program 6.8A<br />

Cont<strong>in</strong>ued<br />

if ( operator == '+' )<br />

pr<strong>in</strong>tf ("%.2f\n", value1 + value2);<br />

else if ( operator == '-' )<br />

pr<strong>in</strong>tf ("%.2f\n", value1 - value2);<br />

else if ( operator == '*' )<br />

pr<strong>in</strong>tf ("%.2f\n", value1 * value2);<br />

else if ( operator == '/' )<br />

if ( value2 == 0 )<br />

pr<strong>in</strong>tf ("Division by zero.\n");<br />

else<br />

pr<strong>in</strong>tf ("%.2f\n", value1 / value2);<br />

else<br />

pr<strong>in</strong>tf ("Unknown operator.\n");<br />

}<br />

return 0;<br />

Program 6.8A<br />

Output<br />

Type <strong>in</strong> your expression.<br />

123.5 + 59.3<br />

182.80<br />

Program 6.8A Output (Rerun)<br />

Type <strong>in</strong> your expression.<br />

198.7 / 0<br />

Division by zero.<br />

Program 6.8A Output (Second Rerun)<br />

Type <strong>in</strong> your expression.<br />

125 $ 28<br />

Unknown operator.<br />

When the operator that is typed <strong>in</strong> is the slash, for division, another test is made to<br />

determ<strong>in</strong>e if value2 is 0. If it is, an appropriate message is displayed at the term<strong>in</strong>al.<br />

Otherwise, the division operation is carried out and the results are displayed. Pay careful<br />

attention to the nest<strong>in</strong>g of the if statements and the associated else clauses <strong>in</strong> this case.<br />

The else clause at the end of the program catches any “fall throughs.”Therefore, any<br />

value of operator that does not match any of the four characters tested causes this else<br />

clause to be executed, result<strong>in</strong>g <strong>in</strong> the display of “Unknown operator.”

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!