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
Show 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.