Check if a Year is a Leap Year Using a Function in C++

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 occur every four years to help synchronize the calendar year with the solar year. However, the actual rule is a bit more complex and includes exceptions for years divisible by 100 but not by 400.

You will implement a function that takes an integer year as input and applies the leap year logic: a year is a leap year if it is divisible by 4, but not by 100 unless it is also divisible by 400. This exercise is great for practicing conditional statements and function definitions in C++.

By completing this task, you'll gain a stronger understanding of logical operations and decision-making structures in programming.

Group

Functions in C++

Objective

1. Write a function that receives an integer year as a parameter.
2. Inside the function, use if-else statements to check if the year satisfies the leap year rules.
3. Return true if the year is a leap year; otherwise, return false.
4. In the main function, prompt the user to enter a year and call the function.
5. Display whether the entered year is a leap year or not.

Create a function that determines if a year is a leap year.

Example C++ Exercise

 Copy C++ Code
#include <iostream> // Include the iostream library for input and output

using namespace std; // Use the standard namespace

// Function to determine if a year is a leap year
bool isLeapYear(int year) {
    // A year is a leap year if it is divisible by 4 and not divisible by 100,
    // unless it is also divisible by 400
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
        return true; // It is a leap year
    } else {
        return false; // It is not a leap year
    }
}

// Main function - entry point of the program
int main() {
    int year; // Variable to store the input year

    // Ask the user to enter a year
    cout << "Enter a year: ";
    cin >> year; // Read the year from user input

    // Call the function to check if it is a leap year
    if (isLeapYear(year)) {
        // If true, print this message
        cout << year << " is a leap year." << endl;
    } else {
        // If false, print this message
        cout << year << " is not a leap year." << endl;
    }

    return 0; // End of the program
}

 Output

Enter a year: 2024
2024 is a leap year.

Share this C++ Exercise


More C++ Programming Exercises of Functions in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.