20.09.2015 Views

Programming in C

Kochan - ProgramminginC

Kochan - ProgramminginC

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

66 Chapter 6 Mak<strong>in</strong>g Decisions<br />

The if statement is used to stipulate execution of a program statement (or statements if<br />

enclosed <strong>in</strong> braces) based upon specified conditions. I will go swimm<strong>in</strong>g if it is not ra<strong>in</strong><strong>in</strong>g.<br />

Similarly, <strong>in</strong> the program statement<br />

if ( count > COUNT_LIMIT )<br />

pr<strong>in</strong>tf ("Count limit exceeded\n");<br />

the pr<strong>in</strong>tf statement is executed only if the value of count is greater than the value of<br />

COUNT_LIMIT; otherwise, it is ignored.<br />

An actual program example helps drive this po<strong>in</strong>t home. Suppose you want to write a<br />

program that accepts an <strong>in</strong>teger typed <strong>in</strong> from the term<strong>in</strong>al and then displays the<br />

absolute value of that <strong>in</strong>teger. A straightforward way to calculate the absolute value of an<br />

<strong>in</strong>teger is to simply negate the number if it is less than zero.The use of the phrase “if it is<br />

less than zero” <strong>in</strong> the preced<strong>in</strong>g sentence signals that a decision must be made by the<br />

program.This decision can be affected by the use of an if statement, as shown <strong>in</strong><br />

Program 6.1.<br />

Program 6.1 Calculat<strong>in</strong>g the Absolute Value of an Integer<br />

// Program to calculate the absolute value of an <strong>in</strong>teger<br />

<strong>in</strong>t ma<strong>in</strong> (void)<br />

{<br />

<strong>in</strong>t number;<br />

pr<strong>in</strong>tf ("Type <strong>in</strong> your number: ");<br />

scanf ("%i", &number);<br />

if ( number < 0 )<br />

number = -number;<br />

pr<strong>in</strong>tf ("The absolute value is %i\n", number);<br />

}<br />

return 0;<br />

Program 6.1 Output<br />

Type <strong>in</strong> your number: -100<br />

The absolute value is 100<br />

Program 6.1 Output (Rerun)<br />

Type <strong>in</strong> your number: 2000<br />

The absolute value is 2000

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

Saved successfully!

Ooh no, something went wrong!