Leap year finding – CSKC
Sign In

Search

Solved Problem #CPP#2008    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

 

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

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

Created: 29-Dec-2017 12:36 | Updated: 18-Dec-2018 18:33|