A year with 366 days is called a leap year. A year is a leap year if it is divisible by four (for example, 1980), except that it is not a leap year if it is divisible by 100 (for example, 1900); however, it is a leap year if it is divisible by 400 (for example, 2000). There were no exceptions before the introduction of the Gregorian calendar on October 15, 1582 (1500 was a leap year).
Write a program in C++ that asks the user for a year and computes whether that year is a leap year.
Please find the code for the following:
Code:
#include <iostream>
using namespace std;
int main()
{
int year;
//Accept the user input
cout<<"Enter a year: ";
cin>>year;
//We need to change the order of the conditions which is mentioned
in the question
//Because - Consider the year 1900, in the first condition which is
provided in the
//question, we need to check if it is divisible by 4 then
100.
//1900 is divisible by 4, as per the Condition it should be a leap
year
//But 1900 is not a leap year, since as per the second Condition it
is divisible by 100
//So, To avoid all this, I just changeed the order as per the
logic
//Since there are no Exceptions for the year till 1582, we made
extra cases for that
if (year < 1582 && year % 4 == 0)
cout<<year<<" is a leap year";
else if (year < 1582)
cout<<year<<" is not a leap year";
else if (year >= 1582)
{
//Condition 3: It is a leap year if it is divisible by 400
//check if it is divisible by 4, then it is a leap year
if(year%400==0)
cout<<year<<" is a leap year";
//Condition 2: It is not a leap year if it is divisible by
100
//Check if it is divisible by 100,then it is not leap year
else if(year%100 == 0)
cout<<year<<" is a not a leap year";
//Condition 1: A year is a leap year if it is divisible by
four
//Check if it is divisible by 4, then it is a leap year
else if(year % 4==0)
cout<<year<<" is a leap year";
//Finally, if is not divisible by any ,then not a leap year
else
cout<<year<<" is a not leap year";
}
return 0;
}
Please check the
compiled program and its output for your reference:
Output:
Sample case-1:
Sample
case-2:
Sample
case-3:
Sample
case-4:
(I believe that I made the code simple and understandable. If you still have any query, Feel free to drop me a comment)
Hope this Helps!!!
Please upvote as well, If you got the answer?
If not please comment, I will Help you with that...
Get Answers For Free
Most questions answered within 1 hours.