Skip to content
Related Articles

Related Articles

C++ Program to Check Leap Year

View Discussion
Improve Article
Save Article
  • Last Updated : 21 Jun, 2022

What is a leap yaer?

A year consisting 366 days is a leap year. 

How to identify a year is leap or not:

A year is a leap year if the following conditions are satisfied: 

  1. The year is multiple of 400.
  2. The year is multiple of 4 and not multiple of 100.

Following is pseudo-code:

if year is divisible by 400 then is_leap_year
else if year is divisible by 100 then not_leap_year
else if year is divisible by 4 then is_leap_year
else not_leap_year

C++




// C++ program to check if a given
// year is leap year or not
#include <bits/stdc++.h>
using namespace std;
 
bool checkYear(int year)
{
    // If a year is multiple of 400,
    // then it is a leap year
    if (year % 400 == 0)
        return true;
 
    // Else If a year is multiple of 100,
    // then it is not a leap year
    if (year % 100 == 0)
        return false;
 
    // Else If a year is multiple of 4,
    // then it is a leap year
    if (year % 4 == 0)
        return true;
    return false;
}
 
// Driver code
int main()
{
    int year = 2000;
 
    checkYear(year) ? cout << "Leap Year":
                      cout << "Not a Leap Year";
    return 0;
}

Output: 

Leap Year

Time Complexity: Since there are only if statements in the program , its time complexity is O(1).

Auxiliary Space: O(1)

How to write the above code in one line? 

C++




// One line C++ program to check if a
// given year is leap year or not
#include <bits/stdc++.h>
using namespace std;
 
bool checkYear(int year)
{
     
    // Return true if year is a multiple
    // 0f 4 and not multiple of 100.
    // OR year is multiple of 400.
    return (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0));
}
 
// Driver code
int main()
{
    int year = 2000;
 
    checkYear(year)?
    cout << "Leap Year":
    cout << "Not a Leap Year";
    return 0;
}
 
// This code is contributed by Akanksha Rai

Output: 

Leap Year

Time Complexity: Since there are only if statements in the program , its time complexity is O(1).

Auxiliary Space: O(1)

Check Leap Year using Macros in C/C++

The program outputs 1 if the year is a leap and 0 if it’s not a leap year.

C++




// C++ implementation to check
// if the year is a leap year
// using macros
 
#include <iostream>
using namespace std;
 
// Macro to check if a year
// is a leap year
#define ISLP(y) ((y % 400 == 0) ||
(y % 100 != 0) && (y % 4 == 0))
        
// Driver Code
int main()
{
    int year = 2020;
    cout << ISLP(year) << "";
    return 0;
}

Output:

Leap Year

Time Complexity: Since there are only if statements in the program , its time complexity is O(1).

Auxiliary Space: O(1)

Please refer complete article on Program to check if a given year is leap year for more details!


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!