C++ Leap Year Checker: Mastering the LogicDiscover the secrets of leap years in C++ and learn how to implement them using if…else ladders, nested if statements, and logical operators.

Unlocking the Secrets of Leap Years in C++

The Basics of Leap Years

Do you know what makes a year a leap year? It’s quite simple, really. All years that are perfectly divisible by 4 are leap years, except for century years (years ending with 00), which are only leap years if they are perfectly divisible by 400.

Checking Leap Years with if…else Ladders

Let’s start with a simple example. We’ll ask the user to enter a year, and then use an if…else ladder to check whether it’s a leap year or not. The output will be a straightforward “yes” or “no”. Take a look at the code below:


#include <iostream>

int main() {
    int year;
    std::cout << "Enter a year: ";
    std::cin >> year;

    if (year % 4 == 0) {
        if (year % 100 == 0) {
            if (year % 400 == 0)
                std::cout << "Yes, it's a leap year." << std::endl;
            else
                std::cout << "No, it's not a leap year." << std::endl;
        } else
            std::cout << "Yes, it's a leap year." << std::endl;
    } else
        std::cout << "No, it's not a leap year." << std::endl;

    return 0;
}

Taking it to the Next Level with Nested if Statements

Now, let’s get a bit more advanced. We’ll use nested if statements to check whether the year entered by the user is a leap year or not. Here’s how it works:

  • First, we check if the year is divisible by 4. If not, it’s not a leap year.
  • If it is divisible by 4, we use an inner if statement to check whether it’s divisible by 100. If not, it’s still a leap year.
  • But what about century years? We know they’re not leap years unless they’re divisible by 400. So, if the year is divisible by 100, we use another inner if statement to check whether it’s divisible by 400. If it is, it’s a leap year. Otherwise, it’s not.

Leave a Reply