In this post, you will learn to check whether a year is a leap year or not using the C++ programming language. But before moving to the coding part it is important to get some basic understanding of Leap Year. Let's start this topic with our first question and that is:
What is Leap Year?
A Year that contains 366 days is known as Leap Year. We get one leap year every four years and this year February month contains 29 days which is one extra day than any usual year. Examples of Leap Years: 1968, 2000, 2004, 2012, etc.
How to Check if a Year is Leap Year or not?
There are certain conditions that you can check to find out whether a year is a leap year or not.
- If the given year is divisible by 400 then it is a leap year.
- If the given year is divisible by 100 but not divisible by 400 then it is not a leap year.
- If the given year is divisible by 4 but is not divisible by 100 then it is a leap year.
- If both the above conditions fail to satisfy then the given year is not a leap year.
C++ Program to check Leap Year using if else statement.
//C++ Code to check Leap year using if else. #include<iostream> using namespace std; int main(){ int year; cout<<"Enter a Year: "; cin>>year; //Year divisible by 400 if(year % 400 == 0) cout<<year<<" is a Leap Year."; //Year divisible by 100 but not divisible by 400 else if(year % 100 == 0) cout<<year<<" is not a Leap Year."; //Year divisible by 4 but not divisible by 100 else if(year % 4 == 0) cout<<year<<" is a Leap Year."; else cout<<year<<" is not a Leap Year."; return 0; }
Enter a Year: 1968 1968 is a Leap Year.
C++ Program to check Leap Year using nested if else statement.
//C++ Code to check Leap year using nested if else. #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."; } 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; }
Enter a Year: 2006 2006 is not a Leap Year.
No comments:
Post a Comment