Programming in C

(Barry) #1
The ifStatement 71

When writing programs, this “else” concept is so frequently required that almost all
modern programming languages provide a special construct to handle this situation. In
C,this is known as the if-elseconstruct and the general format is as follows:
if ( expression)
program statement 1
else
program statement 2
The if-elseis actually just an extension of the general format of the ifstatement. If
the result of the evaluation of expressionis TRUE,program statement 1, which
immediately follows, is executed; otherwise,program statement 2is executed. In either
case, either program statement 1or program statement 2is executed, but not both.
You can incorporate the if-elsestatement into Program 6.3, replacing the two if
statements with a single if-elsestatement.The use of this new program construct actu-
ally helps to reduce the program’s complexity and also improves its readability, as shown
in Program 6.4.

Program 6.4 Revising the Program to Determine if a Number Is Even or Odd
// Program to determine if a number is even or odd (Ver. 2)

#include <stdio.h>

int main ()
{
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");
else
printf ("The number is odd.\n");

return 0;
}

Program 6.4 Output
Enter your number to be tested: 1234
The number is even.

TEAM FLY

Free download pdf