Home »
C++ Programs
C++ program to print the leap years in the given time period using class
Submitted by Shubh Pachori, on September 01, 2022
Problem statement
Given two years, we have to print the leap years between them using the class and object approach.
Example:
Input:
Enter Time Period : 2015 2019
Output:
Leap Years between 2015 and 2019 are
2016
C++ code to print the leap years in the given time period using the class and object approach
#include <iostream>
#include <string>
using namespace std;
// create a class
class Leap {
// private data members
private:
int start_year, end_year;
// public member functions
public:
// getTimePeriod() function to input time period
void getTimePeriod() {
cout << "Enter Time Period : ";
cin >> start_year >> end_year;
}
// isLeap() function to print leap years in the
// inputted time period
void isLeap() {
// initializing int type variables to perform
// operations and manipulations
int index, check = 1;
cout << "Leap Years between " << start_year << " and " << end_year
<< " are " << endl;
// for loop to check if there is a leap year
// in between the time period
for (index = start_year; index <= end_year; index++) {
// if condition for century leap years
if (index % 400 == 0) {
cout << index << " ";
check = 0;
}
// if condition for century non leap year
else if (index % 100 == 0) {
}
// if condition for non century leap year
else if (index % 4 == 0) {
cout << index << " ";
check = 0;
}
// else for all non leap years
else {
}
}
// if condition to print if there is no leap year
// in the inputted time period
if (check != 0) {
cout << "No Leap year found!" << endl;
}
}
};
int main() {
// create an object
Leap L;
// calling getTimePeriod() function to
// input time period
L.getTimePeriod();
// calling isLeap() function to
// print leap years
L.isLeap();
return 0;
}
Output
RUN 1:
Enter Time Period: 2000 2020
Leap Years between 2000 and 2020 are
2000 2004 2008 2012 2016 2020
RUN 2:
Enter Time Period : 1900 1999
Leap Years between 1900 and 1999 are
1904 1908 1912 1916 1920 1924 1928 1932 1936 1940 1944 1948
1952 1956 1960 1964 1968 1972 1976 1980 1984 1988 1992 1996
Explanation
In the above code, we have created a class Leap, two int type data members start_year and end_year to store the time period, and a public member functions getTimePeriod() and isLeap() to store the inputted time period and print leap year between period.
In the main() function, we are creating an object L of class Leap, reading time period by the user using getTimePeriod() function, and finally calling the isLeap() member function to print the leap years between the inputted time period. The isLeap() function contains the logic to print leap years between the time period.
C++ Class and Object Programs (Set 2) »