Example(s):Palindrome, prime, armstrong, "linear search", reverse etc.

Example(s):1575, 1632, 1539 (Only one at a time)

Login

[lwa]

Solved Problem#CPP#2008

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 <iostream.h>
#include <conio.h>
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 "<<year<<" is a leap year.";
else
cout<<"Given year "<<year<<" is not a leap year.";
getch();
return 0;
}

#include <iostream>
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 "<<year<<" is a leap year.";
else
cout<<"Given year "<<year<<" is not a leap year.";
return 0;
}

Before using this you should have copied the code by selecting the entire code and pressing cntrl-c. (Line numbers will not come in the copied code). After that open any of the service and press cntrl-v to paste in the given code area. Needs a bit of tweaking as per the link.

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.

Solved Problem Understanding

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.

Code 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;