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.

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

Program 6.3 Determ<strong>in</strong><strong>in</strong>g if a Number Is Even or Odd<br />

// Program to determ<strong>in</strong>e if a number is even or odd<br />

#<strong>in</strong>clude <br />

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

{<br />

<strong>in</strong>t number_to_test, rema<strong>in</strong>der;<br />

pr<strong>in</strong>tf ("Enter your number to be tested.: ");<br />

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

rema<strong>in</strong>der = number_to_test % 2;<br />

if ( rema<strong>in</strong>der == 0 )<br />

pr<strong>in</strong>tf ("The number is even.\n");<br />

if ( rema<strong>in</strong>der != 0 )<br />

pr<strong>in</strong>tf ("The number is odd.\n");<br />

}<br />

return 0;<br />

Program 6.3 Output<br />

Enter your number to be tested: 2455<br />

The number is odd.<br />

Program 6.3 Output (Rerun)<br />

Enter your number to be tested: 1210<br />

The number is even.<br />

After the number is typed <strong>in</strong>, the rema<strong>in</strong>der after division by 2 is calculated.The first if<br />

statement tests the value of this rema<strong>in</strong>der to see if it is equal to zero. If it is, the message<br />

“The number is even” is displayed.<br />

The second if statement tests the rema<strong>in</strong>der to see if it’s not equal to zero and, if<br />

that’s the case, displays a message stat<strong>in</strong>g that the number is odd.<br />

The fact is that whenever the first if statement succeeds, the second one must fail,<br />

and vice versa. Recall from the discussions of even/odd numbers at the beg<strong>in</strong>n<strong>in</strong>g of this<br />

section that if the number is evenly divisible by 2, it is even; else it is odd.

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

Saved successfully!

Ooh no, something went wrong!