Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Chapter 4. C++ Control Flow > Iteration - Pg. 112

C++ Control Flow if (year % 400 != 0) // divisible by 100 but not by 400) cout <<"Year "<<year<<" is not a leap year" <<endl; else // divisible by 4, by 100 and by 400 cout <<"Year " << year <<" is a leap year" << endl; else // divisible by 4 but not divisible by 100 cout << "Year " << year << " is a leap year" << endl; 112 Now you can combine the two conditions that follow each other using the AND operation, and the last two clauses for a leap year can be combined, too. That gives a more concise solution: if (year % 4 != 0) // not divisible by 4, period cout <<"Year " << year <<" is not a leap year" << endl; else if (year % 100==0 && year % 400!=0)// by 100 but not by 400 cout <<"Year "<<year<<" is not a leap year" <<endl; else // divisible by 4 but not divisible by 100 cout << "Year " << year << " is a leap year" << endl; Isn't this nice? There are only two levels of nesting, and this is quite acceptable. But the same processing related to non-leap year is repeated, and this is not good enough for a C++ programmer. The year is not a leap year when the year is not divisible by four or when the condition (year % 100 == 0 and year % 400 != 0) is true. This calls for the OR operation, right? Listing 4.9 gives us the answer that is not only correct and efficient, but also is concise and elegant. Example 4.9. An optimized solution to the leap year problem. #include <iostream> using namespace std; int main () { int year;