Programming in C

(Barry) #1

70 Chapter 6 Making Decisions


Program 6.3 Determining if a Number Is Even or Odd
// Program to determine if a number is even or odd

#include <stdio.h>

int main (void)
{
int number_to_test, remainder;

printf ("Enter your number to be tested.: ");
scanf ("%i", &number_to_test);

remainder = number_to_test % 2;

if ( remainder == 0 )
printf ("The number is even.\n");

if ( remainder != 0 )
printf ("The number is odd.\n");

return 0;
}

Program 6.3 Output
Enter your number to be tested: 2455
The number is odd.

Program 6.3 Output (Rerun)
Enter your number to be tested: 1210
The number is even.

After the number is typed in, the remainder after division by 2 is calculated.The first if
statement tests the value of this remainder to see if it is equal to zero. If it is, the message
“The number is even” is displayed.
The second ifstatement tests the remainder to see if it’s notequal to zero and, if
that’s the case, displays a message stating that the number is odd.
The fact is that whenever the first ifstatement succeeds, the second one must fail,
and vice versa. Recall from the discussions of even/odd numbers at the beginning of this
section that if the number is evenly divisible by 2, it is even;elseit is odd.
Free download pdf