Check if a Year is a Leap Year Using Functions

Check for Leap Year

This exercise teaches you how to create a function in C++ to determine whether a given year is a leap year or not. Leap years help synchronize the calendar year with the solar year, occurring roughly every four years.

However, the actual rule includes specific exceptions: a year is a leap year if it is divisible by 4, but not by 100 unless it is also divisible by 400. You will implement this logic using a modular approach.

Implementation Details

1. Boolean Logic

Using bool as a return type is the most efficient way to represent "Yes/No" or "True/False" conditions.

2. Modulo Operator

The % operator is essential here to check divisibility (e.g., year % 4 == 0).

3. Logical Operators

Combining conditions with && (AND) and || (OR) allows for a concise, one-line rule.

Objective

  • 1. Define a function isLeapYear(int year).
  • 2. Implement the nested logic: (divisible by 4 AND NOT 100) OR (divisible by 400).
  • 3. Return a bool value based on the result.
  • 4. Use an if statement in main() to print a user-friendly message.

Example C++ Exercise

leap_year_check.cpp Boolean Functions
#include <iostream>

using namespace std;

// Function to determine if a year is a leap year
bool isLeapYear(int year) {
    // Logic: (divisible by 4 AND not 100) OR (divisible by 400)
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
        return true; 
    } else {
        return false;
    }
}

int main() {
    int year;

    cout << "Enter a year: ";
    cin >> year;

    // Call the function to check if it is a leap year
    if (isLeapYear(year)) {
        cout << year << " is a leap year." << endl;
    } else {
        cout << year << " is not a leap year." << endl;
    }

    return 0;
}

Example Output:

Enter a year: 2024
2024 is a leap year.
Related Topics
Boolean Types Modulo Arithmetic Nested If-Else Logical AND/OR

Share this C++ Exercise

Help others master conditional logic!

© C++ Programming Exercises. Master the art of performance coding.