Monday 1 October 2018

Checking whether a year is a leap year or not in C++

Leap year


The Earth takes 365 days and 6 hours for a complete revolution around the Sun. The 6 hours becomes 24 hours after four years. This 24 hours or a day is added to a year in every four years. The year which contains an additional day(i.e. leap day) in a calendar year is called leap year. The additional day is added to February. So a leap year has 366 days and 29 days in the month February instead of 28. According to the Gregorian calendar, the following statement identifies a leap year.
A year that is exactly divisible by four is a leap year, except for the years that are exactly divisible by 100, but these centennials(years ending with 00) are leap years if they are exactly divisible by 400.
1600 and 2000 are leap years but 1700, 2100, 2300 are common years.


Write a program in C++ to input a year from the user and check whether it is a leap year or not.


In this program, we input a year(integer data type) from the user. Then we check all the condition required to be a leap year. If all the condition satisfies then it is a leap year, else it is a common year.


Program


#include<iostream.h>
#include<conio.h>
void main()
{
int year;
clrscr();
cout<<"Enter a year=";
cin>>year;
cout<<endl;
if((year%4)!=0)
cout<<year<<" is a common year";
else if((year%100)!=0)
cout<<year<<" is a leap year";
else if((year%400)!=0)
cout<<year<<" is a common year";
else
cout<<year<<" is a leap year";
getch();

}



Output


Checking leap year
PROGRAM TO CHECK LEAP YEAR











Explanation


In this program, the entered year is 1600(i.e. year=1600). 

Condition                            Result                           
(1600%4)!=0                        False as 1600%4=0
(1600%100)!=0                    False as 1600%100=0
(1600%400)!=0                    False as 1600%400=0
else                                      True

So, 1600 is a leap year message was printed on the screen.








No comments:

Post a Comment