Friday, 14 June 2024

Leap Year in C++

Problem Description
For an input year N, find whether the year is a leap or not.

Input format
First line contains an integer - N.

Output format
Print "true" if it is a leap year otherwise "false".

Sample Input 1
1600

Sample Output 1
true

Explanation
Year 1600 is a leap year

Sample Input 2
1800

Sample Output 2
false

Explanation
Year 1800 is not a leap year

Constraints
1 <= N <= 9999

Solution
To determine if a given year \( N \) is a leap year, we need to follow the rules of the Gregorian calendar:

1. A year is a leap year if it is divisible by 4.
2. However, if the year is divisible by 100, it is not a leap year unless:
3. The year is also divisible by 400, in which case it is a leap year.

Based on these rules, we can implement a C++ program that reads a year \( N \) and determines if it is a leap year.

### C++ Code

#include <iostream>
using namespace std;

int main() {
    int N;
    cin >> N;
    
    bool isLeapYear = false;
    
    if (N % 4 == 0) {
        if (N % 100 == 0) {
            if (N % 400 == 0) {
                isLeapYear = true;
            } else {
                isLeapYear = false;
            }
        } else {
            isLeapYear = true;
        }
    } else {
        isLeapYear = false;
    }
    
    if (isLeapYear) {
        cout << "true" << endl;
    } else {
        cout << "false" << endl;
    }
    
    return 0;
}

### Explanation

1. **Input Handling**: The program reads an integer \( N \) from the standard input.
2. **Leap Year Check**:
   - First, it checks if \( N \) is divisible by 4.
   - If \( N \) is divisible by 4, it then checks if \( N \) is divisible by 100.
   - If \( N \) is divisible by 100, it further checks if \( N \) is divisible by 400.
   - Based on these checks, the program sets the `isLeapYear` flag to `true` or `false`.
3. **Output**: The program prints "true" if `isLeapYear` is `true`, otherwise it prints "false".

### Sample Runs

#### Sample Input 1
1600

#### Sample Output 1
true

#### Explanation
Year 1600 is divisible by 400, so it is a leap year.

#### Sample Input 2
1800

#### Sample Output 2
false

#### Explanation
Year 1800 is divisible by 100 but not by 400, so it is not a leap year.

This program efficiently determines whether a given year is a leap year based on the rules of the Gregorian calendar.

No comments:

Post a Comment