Programming in C

(Barry) #1
The ifStatement 73

To illustrate the use of a compound relational test in an actual program example,
write a program that tests to see whether a year is a leap year. A year is a leap year if it is
evenly divisible by 4.What you might not realize, however, is that a year that is divisible
by 100 is nota leap year unless it also is divisible by 400.
Tr y to think how you would go about setting up a test for such a condition. First,
you could compute the remainders of the year after division by 4, 100, and 400, and
assign these values to appropriately named variables, such as rem_4,rem_100, and
rem_400,respectively.Then, you could proceed to test these remainders to determine if
the desired criteria for a leap year are met.
If you rephrase the previous definition of a leap year, you can say that a year is a leap
year if it is evenly divisible by 4 and not by 100 or if it is evenly divisible by 400. Stop
for a moment to reflect on this last sentence and to verify to yourself that it is equivalent
to our previously stated definition. Now that you have reformulated our definition in
these terms, it becomes a relatively straightforward task to translate it into a program
statement as follows:


if ( (rem_4 == 0 && rem_100 != 0) || rem_400 == 0 )
printf ("It's a leap year.\n");


The parentheses around the subexpression


rem_4 == 0 && rem_100 != 0


are not required because that is how the expression will be evaluated anyway.
If you add a few statements in front of this test to declare your variables and to enable
the user to key in the year from the terminal, you end up with a program that deter-
mines if a year is a leap year, as shown in Program 6.5.


Program 6.5 Determining if a Year Is a Leap Year


// Program to determines if a year is a leap year


#include <stdio.h>


int main (void)
{
int year, rem_4, rem_100, rem_400;


printf ("Enter the year to be tested: ");
scanf ("%i", &year);

rem_4 = year % 4;
rem_100 = year % 100;
rem_400 = year % 400;

if ( (rem_4 == 0 && rem_100 != 0) || rem_400 == 0 )
printf ("It's a leap year.\n");
Free download pdf