Day 24: Leap Year Checker

Objective

Write a program that determines whether a given year is a leap year. Leap years occur every 4 years, with some exceptions:

  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.
  3. Unless the year is also divisible by 400, in which case it is a leap year.

For example:

  • Input: 2024 → Output: “2024 is a leap year.”
  • Input: 1900 → Output: “1900 is not a leap year.”
  • Input: 2000 → Output: “2000 is a leap year.”

Why This Challenge Is Important

This challenge is a great way to practice conditional logic and modulo operations. It also demonstrates how logical rules can translate into code. Understanding leap years is an essential problem-solving exercise, often used in real-world applications like calendar systems and date validation.


Steps to Solve

1. Understand the Problem

The rules for identifying a leap year are:

  • If the year is divisible by 4, it might be a leap year.
  • If the year is divisible by 100, it is not a leap year unless it is also divisible by 400.

2. Plan Your Solution

  1. Take the input year from the user.
  2. Use conditional statements to check the divisibility rules.
  3. Output whether the year is a leap year or not.

3. Enhancements to Consider

  • Validate the user’s input to ensure it’s a valid year (e.g., non-negative integers).
  • Allow the user to check multiple years without restarting the program.

Code Examples

Python Example

print("Welcome to the Leap Year Checker!")

while True:
    try:
        # Get the year as input
        year = int(input("Enter a year (or type -1 to quit): "))

        if year == -1:
            print("Goodbye!")
            break

        # Check if it's a leap year
        if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
            print(f"{year} is a leap year.")
        else:
            print(f"{year} is not a leap year.")
    except ValueError:
        print("Please enter a valid integer.")

Java Example

import java.util.Scanner;

public class LeapYearChecker {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Welcome to the Leap Year Checker!");

        while (true) {
            System.out.print("Enter a year (or type -1 to quit): ");
            int year = scanner.nextInt();

            if (year == -1) {
                System.out.println("Goodbye!");
                break;
            }

            // Check if it's a leap year
            if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
                System.out.println(year + " is a leap year.");
            } else {
                System.out.println(year + " is not a leap year.");
            }
        }
    }
}

JavaScript Example

console.log("Welcome to the Leap Year Checker!");

while (true) {
    let input = prompt("Enter a year (or type -1 to quit):");

    if (input === "-1") {
        console.log("Goodbye!");
        break;
    }

    let year = parseInt(input);

    if (isNaN(year)) {
        console.log("Please enter a valid integer.");
        continue;
    }

    // Check if it's a leap year
    if ((year % 4 === 0 && year % 100 !== 0) || (year % 400 === 0)) {
        console.log(`${year} is a leap year.`);
    } else {
        console.log(`${year} is not a leap year.`);
    }
}

Edge Cases to Consider

  1. Years Less Than 0: Technically, leap years didn’t exist in negative years, but your program can still check them if needed.
  2. Non-Numeric Input: Handle cases where the user enters something other than a number.
  3. Very Large Numbers: Ensure the program can handle large year inputs without crashing.

Extensions to Explore

  1. Range Checking: Allow the user to input a range of years and display all the leap years in that range.
  2. Historical Insights: Inform the user about the Gregorian calendar’s introduction in 1582 and handle older years accordingly.
  3. Next Leap Year: If the input year is not a leap year, display the next leap year.

What You’ve Learned

  • How to use logical conditions and modulo operations.
  • How to implement real-world rules into programming logic.
  • How to validate user input and handle edge cases.

Next Steps

In Day 25: Number Guessing Game, you’ll create an interactive Number Guessing Game where the computer generates a random number, and the user tries to guess it.