SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
.loops
Exercise:
Programming Excercises
Question:29 | ISBN:978013274719 | Edition: 6

Question

(Display leap years) Write a program that displays, ten per line, all the leap years in the twenty-first century (from year 2001 to 2100). The years are separated by exactly one space.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Display leap years Program code:

# Define the starting and ending years
startYear = 2001
endYear = 2100

# Initialize a counter for leap years
leapYearCount = 0

# Iterate over the years in the range
for year in range(startYear, endYear + 1):
    # Check if the year is a leap year
    if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
        # Display the leap year
        print(year, end=" ")
        
        # Increment the leap year counter
        leapYearCount += 1
        
        # Check if we have printed ten leap years
        if leapYearCount % 10 == 0:
            # Start a new line
            print()

# Print a new line if the last line doesn't contain 10 years
if leapYearCount % 10 != 0:
    print()

Executed Output:

2004 2008 2012 2016 2020 2024 2028 2032 2036 2040 
2044 2048 2052 2056 2060 2064 2068 2072 2076 2080 
2084 2088 2092 2096 

 

 

0 0

Discussions

Post the discussion to improve the above solution.