C++ Program to check Whether the given year is a leap year or not (3 Ways)

In this article, we will discuss how to check whether a given year is a leap year or not using C++ programming language.

Firstly, let’s discuss “What is Leap year?“.

It’s a year which is exactly divisible by 4 except for the years ending with double zero(00) (also called century years). And among the century years, only those years are the leap year which is perfectly divisible by 400.

I will be discussing 3 different ways to write the C++ program for it.

  1. Using if statement
  2. Using the if-else statement
  3. Using nested if-else statement

Let’s discuss all the ways one by one.

C++ programming Code to check for Leap Year

Using if statement

In this program, I have used three if statements. And the order in which these if statements are used is should be in exact order which is being displayed below otherwise the program will not work correctly.

Code:-

#include <iostream>

using namespace std;

int main(){
    int year;

    cout << "Enter a year: ";
    cin >> year;

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

Output:-

Enter a year: 2000
2000 is a leap year.

Using the if-else statement

In this program, I have use if-else statement. Give more attention to how the conditional statements are used.

Code:-

#include <iostream>

using namespace std;

int main(){
    int year;

    cout << "Enter a year: ";
    cin >> year;

   if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
      cout << year << " is a leap year." << endl;
   else
      cout << year << " is not a leap year." << endl;

    return 0;
}

Output:-

Enter a year: 2016
2016 is a leap year.

Using nested if-else statement

In this program, I have used the nested if-else statement.

Code:-

#include <iostream>

using namespace std;

int main(){
    int year;

    cout << "Enter a year: ";
    cin >> year;

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

    return 0;
}

Output:-

Enter a year: 2016
2016 is a leap year.

You can learn about many other C++ Programs Here.

Best Books for learning C++ programming language with Data Structure and Algorithms.

The following two tabs change content below.
Amit Rawat

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...