What is a Leap Year?
A leap year is a year that is exactly divisible by 4, except for years that are divisible by 100. However, years that are divisible by 400 are also leap years.
#include <iostream>
using namespace std;
int main() {
int year;
cout << "Enter a year: ";
cin >> year;
// Leap year logic
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0)
cout << year << " is a leap year";
else
cout << year << " is not a leap year";
} else
cout << year << " is a leap year";
} else
cout << year << " is not a leap year";
return 0;
}
//===========
OUTPUT:
Enter a year: 2020
2020 is a leap year
Enter a year: 1900
1900 is not a leap year
Enter a year: 2000
2000 is a leap year
In this program, we first take input of the year from the user. Then we use the leap year logic to check if the year is a leap year or not.
If the year is divisible by 4 and not divisible by 100, it is a leap year. If the year is divisible by 100, it is a leap year only if it is also divisible by 400. If the year is not divisible by 4, it is not a leap year.
Program Explanation
- We start by including the
<iostream>library which allows us to take input and output operations in C++. - We declare a variable
yearwhich will hold the value of the year to be checked. - We use the
coutstatement to ask the user to enter the year. - We use the
cinstatement to take input of the year from the user and store it in theyearvariable. - We use the leap year logic to check whether the year is a leap year or not. We start by checking if the year is divisible by 4 using the modulus operator
%. If the remainder of the division is 0, it means the year is divisible by 4. - If the year is divisible by 4, we need to check if it is also divisible by 100. If the year is divisible by 100, it is not a leap year, unless it is also divisible by 400. If the year is not divisible by 100, it is a leap year.
- We use
ifandelsestatements to print out the result of the check. If the year is a leap year, we print out a message saying so. If it is not a leap year, we print out a message saying so. - Finally, we use the
return 0statement to exit the program.
Program Notes
- The
using namespace stdstatement is used to avoid having to writestd::before every standard library function or object. - We use the
coutstatement to display a message on the screen. The<<operator is used to insert the message into the output stream. - We use the
cinstatement to take input from the user. The>>operator is used to extract the input from the input stream. - The modulus operator
%is used to find the remainder of a division. - The
ifstatement is used to check if a condition is true. If the condition is true, the statements within theifblock are executed. If the condition is false, the statements within theelseblock are executed. - The
return 0statement is used to indicate that the program has successfully completed execution.
No comments:
Post a Comment