Programming in C

(Barry) #1

74 Chapter 6 Making Decisions


else
printf ("Nope, it's not a leap year.\n");

return 0;
}

Program 6.5 Output
Enter the year to be tested: 1955
Nope, it's not a leap year.

Program 6.5 Output (Rerun)
Enter the year to be tested: 2000
It's a leap year.

Program 6.5 Output (Second Rerun)
Enter the year to be tested: 1800
Nope, it's not a leap year.

The previous examples show a year that was not a leap year because it wasn’t evenly
divisible by 4 (1955), a year that was a leap year because it was evenly divisible by 400
(2000), and a year that wasn’t a leap year because it was evenly divisible by 100 but not
by 400 (1800).To complete the run of test cases, you should also try a year that is evenly
divisible by 4 but not by 100.This is left as an exercise for you.
As mentioned previously, C gives you a tremendous amount of flexibility in forming
expressions. For instance, in the preceding program, you did not have to calculate the
intermediate results rem_4,rem_100,and rem_400—you could have performed the calcu-
lation directly inside the ifstatement as follows:
if ( ( year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0 )
The use of blank spaces to set off the various operators still makes the preceding expres-
sion readable. If you decide to ignore adding blanks and remove the unnecessary set of
parentheses, you end up with an expression that looks like this:
if(year%4==0&&year%100!=0)||year%400==0)
This expression is perfectly valid and (believe it or not) executes identically to the
expression shown immediately prior. Obviously, those extra blanks go a long way toward
aiding understanding of complex expressions.

Program 6.5 Continued
Free download pdf