C++ Program to Check Leap Year (Using nested if-else)

by | Jan 18, 2023 | C++, C++ Programs

Introduction

In this program, you will learn to check the year entered is a leap year or not.

To understand this program, you must have gone through the following C++ topics

1. Operators

2. Nested if-else

To check whether a year is a leap year or not, we have different situations.

All years completely divisible by 4 are leap years except for the values ending with 00.

The year values ending with 00, like 1700,1600, are leap years if perfectly divisible by 400.

Program

#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) // for century years
{
cout<<year<<" is a leap year";
}
else
{
cout<<year<<" is not a leap year";
}
}
else
{
cout<<year<<" is a leap year";
}
}
else
{
cout<<year<<" is not a leap year";
}
return 0;
}

 

Output

Explanation

In this program, the user is asked to enter a value that gets stored in the ‘year’ variable.

To check whether the ‘year’ is a leap year or not, we use a nested if-else statement.

The main condition for a year to be a leap year is that it is perfectly divisible by 4, but all values which are perfectly divisible by 4 do not leap years like 1700 and 1800.

Thus, we check if ‘year’ is divisible by 4 or not.

Now, if we encounter values ending with 00, we will check whether ‘year’ is divisible by 100 or not. If it gives a false result, it is still a leap year since divisible by 4.

If ‘year’ is perfectly divisible by 100, then we will check for 400.

This is for centuries years. Thus, if ‘year’ is divisible by 400, then it is a leap year otherwise not.

 

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.