Leap year finding – Computer Sir Ki Class
  

Login
[lwa]



Solved Problem #CPP#2008 siteicon   siteicon   siteicon  

Problem Statement - Leap year finding

Write a c++ program to take the value of a four digit year from the user and then print whether the given year is a leap year or not.

Solution

TC++ #2008

#include 
#include
int main()
{
clrscr();
int year,leap=0;
cout<<"Enter year (4 Digits) :";
cin>>year ;
if(year%100==0)
{
if(year%400==0) leap=1;
}
else if(year%4==0)leap=1;
if(leap==1)
cout<<"Given year "< else
cout<<"Given year "< getch();
return 0;
}
#include 
using namespace std;
int main()
{
int year,leap=0;
cout<<"Enter year (4 Digits) :";
cin>>year ;
if(year%100==0)
{
if(year%400==0) leap=1;
}
else if(year%4==0)leap=1;
if(leap==1)
cout<<"Given year "< else
cout<<"Given year "< return 0;
}

Test it !

Run Output

Enter year (4 Digits) :2000
Given year 2000 is a leap year.

-OR-
Enter year (4 Digits) :1900
Given year 1900 is not a leap year.

-OR-
Enter year (4 Digits) :1996
Given year 1996 is a leap year.

int year,leap=0;
Hear we declare an integer variable year to collect value of year and also initialise a variable leap as 0 so that it can be used as a flag to be set as 1 when leap condition is true.

cout<<“Enter year (4 Digits) :”; cin>>year ;
Here we collect the 4 digit year value from the user.

if(year%100==0)

{
if(year%400==0) leap=1;
}
This is a nested if within if to test the divisibility by 100 followed by divisibility by 400 to set the flag leap as 1. For century years (divisible by 100) like 1800, 1900, 2000 etc. the leap year is one which is divisible by 400.

else if(year%4==0) leap=1;
Other than the century years leap year has to be fully divisible by 4.

if(leap==1)  cout<<“Given year “<<year<<” is a leap year.”;
else cout<<“Given year “<<year<<” is not a leap year.”;
This simply printing of output based on condition of leap flag.

 

Notes

  • We can do the above program by not using the leap flag the program by directly outputting the message using cout when leap year condition is true. The use of leap flag helps to write the output message at one place. Using such flags is a better way of programming so that the similar messages are not written at multiple places.

Common Errors

  • If we do not use braces { } in the given code here, the dangling else problem may result in incorrect results.
    if(year%100==0)
    {
    if(year%400==0) leap=1;
    }
    else if(year%4==0) leap=1;


Share

sunmitra| Created: 29-Dec-2017 | Updated: 15-Sep-2018|






Back