w3resource

C++ Exercises: Display all the leap years between two given years


Leap Years Between Two Years

Write a C++ program to display all the leap years between two given years. If there is no leap year in the given period,display a suitable message.
Note: Range of the two given years: ( 0 < year1 ≤ year2 < 3,000).

Visual Presentation:

C++ Exercises: Display all the leap years between two given years

Sample Solution:

C++ Code :

#include <iostream>

// Macros for defining range loops
#define range(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
#define rep(i,n) range(i,0,n)

using namespace std;

// Function to check if a year is a leap year
inline bool isleap(int year) {
    if(year % 400 == 0)
        return true;
    if(year % 100 == 0)
        return false;
    if(year % 4 == 0)
        return true;
    return false;
}

int main(void) {
    int a, b;
    bool space = false;

    // Input years
    cin >> a >> b;

    // Output the range of years provided
    cout << "Input years: " << a << " - " << b << endl;

    // Output leap years between the given range of years
    cout << "\nLeap years between said years:\n";

    // Display an empty line if a leap year is found
    if(space) puts("");

    bool ans = false;

    // Loop through the range of years to find leap years
    range(i, a, b + 1) {
        if(isleap(i)) {
            cout << i << endl;
            ans = true;
        }
    }

    // Output if no leap years are found within the range
    if(!ans) puts("No leap years.");

    space = true;

    return 0;
}

Sample Output:

Input years: 1975 - 2018
Leap years between said years:
1976
1980
1984
1988
1992
1996
2000
2004
2008
2012
2016

Flowchart:

Flowchart: Display all the leap years between two given years

For more Practice: Solve these Related Problems:

  • Write a C++ program to list all leap years between two given years and then count the total number of leap years.
  • Write a C++ program that accepts two years, computes the leap years in the range, and prints a formatted list or a message if none exist.
  • Write a C++ program to find and display all leap years between two input years using a loop with proper validation.
  • Write a C++ program that calculates leap years between two given years and then outputs the percentage of leap years within that period.

Go to:


PREV : Sum Positive Integers in Text.
NEXT : Combinations for Given Sum.

C++ Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.