Snippets

Check Leap Year with C++

Posted by I. B. Gd Pramana A. Putra, 12 Mar 22, last updated 17 Jul 22

A C++ code example or code snippet to check leap year. This code is showing you how to create a simple C++ program that checks whether a year is a leap year.

According to Wikipedia: a leap year is a year that has one additional day in order to adjust the calendar to the astronomical year.

The logic to check for leap year:

  • if (year is not divisible by 4) then (it is a common year)
  • else if (year is not divisible by 100) then (it is a leap year)
  • else if (year is not divisible by 400) then (it is a common year)
  • else (it is a leap year)

The years input that we will give & its expected output are:

  • 2020 is a leap year
  • 2019 is not a leap year
  • 2018 is not a leap year
  • 2000 is a leap year
  • 1900 is not a leap year

C++ Code Example to Check for Leap Year You can immediately run the following code in various IDEs that have Dart interpreters such as VS Code, Atom, or CMD.

The following Ruby program code uses the Nested If and Comparison Operators.

int main()
{
    int year;

    cout << "Input year: ";
    cin >> year;

    if (year % 4 == 0)
    {
        if (year % 100 == 0)
        {
            if (year % 400 == 0)
                cout << year << " is a leap year";
            else
                cout << year << " is a not leap year";
        }
        else
            cout << year << " is a leap year";
    }
    else
        cout << year << " is a not leap year";

    return 0;
}

I love sharing code snippets as most of the time, a quick code example is what we're looking for instead of long-written articles. If you think my code snippets are helpful and save you a lot of time, please consider buying me a cup of coffee :)

Support me via · paypal · buymeacoffee · ko-fi · trakteer
Contributed Snippets
Answer & Responses
    No comments yet

Wanna write a response?

You have to login before write a comment to this post.