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?“.
I will be discussing 3 different ways to write the C++ program for it.
- Using if statement
- Using the if-else statement
- 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:-
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:-
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:-
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.
Amit Rawat
Latest posts by Amit Rawat (see all)
- Python Program to Print the Fibonacci Sequence (2 ways) - April 7, 2020
- Python Program to Display or Print Prime Numbers Between a Range or an Interval - June 18, 2019
- Python Program To Print Pascal’s Triangle (2 Ways) - June 17, 2019