Write a program to check leap year.

Checking Leap Years: A Programming Approach

Leap years are years with an extra day (February 29th). They happen to keep our calendar aligned with the Earth's orbit. Accurately figuring out leap years is important for calendars and date calculations in computer programs.

We'll explore how to check for leap years using Python, Java, and C++. Let's dive in!

The Leap Year Algorithm

A year is a leap year if it meets these rules:

  • Divisible by 4
  • But not divisible by 100 unless it's also divisible by 400

Let's break it down into simple steps:

  1. Check if the year is divisible by 4. If not, it's not a leap year.
  2. If it's divisible by 4, check if it's divisible by 100. If it is, it's not a leap year unless it's also divisible by 400.
  3. Otherwise, it's a leap year.

We can use a flowchart here to better illustrate this logical flow (insert flowchart image here).

Python Code for Leap Year Check

Here's a Python function to check for leap years:

def is_leap(year): """Checks if a year is a leap year.""" if year % 4 != 0: return False elif year % 100 == 0: return year % 400 == 0 else: return True # Examples print(is_leap(2000)) # True print(is_leap(2001)) # False print(is_leap(1900)) # False print(is_leap(2024)) # True

The % operator is the modulo operator, giving the remainder of a division.

Java Code for Leap Year Check

Here's the equivalent Java code:

public class LeapYear { public static boolean isLeap(int year) { if (year % 4 != 0) { return false; } else if (year % 100 == 0) { return year % 400 == 0; } else { return true; } } public static void main(String[] args) { System.out.println(isLeap(2000)); // true System.out.println(isLeap(2001)); // false System.out.println(isLeap(1900)); // false System.out.println(isLeap(2024)); // true } }

C++ Code for Leap Year Check

And here's the C++ version:

#include bool isLeap(int year) { if (year % 4 != 0) { return false; } else if (year % 100 == 0) { return year % 400 == 0; } else { return true; } } int main() { std::cout << isLeap(2000) << std::endl; // 1 (true) std::cout << isLeap(2001) << std::endl; // 0 (false) std::cout << isLeap(1900) << std::endl; // 0 (false) std::cout << isLeap(2024) << std::endl; // 1 (true) return 0; }

Beyond the Basics

Input validation: You could add checks to ensure the input is a valid year (e.g., positive integer).

Error Handling: Consider handling potential exceptions, such as non-numeric input.

Challenge: Try to implement this using different programming languages or explore more complex calendar systems.

Wrapping Up

We've covered three different ways to check for leap years. The core logic remains the same across programming languages, highlighting the fundamental nature of the leap year algorithm. Practice writing your own leap year checker!