Skip to the content of the web site.

Project O.1: Printing the Gregorian calendar

Write a program that prints the Gregorian calendar for a given year. The year must be 1583 or later, and January 1, 1583, lands on a Saturday. Every subsequent year has January 1st begin one day of the week later (as (365 % 7) == 1) unless the previous year was a leap year, in which case, January 1st begins two days of the week later.

A year is a leap year if the year is:

  • divisible by 4,
  • but not divisible by 100,
  • unless it is also divisible by 400.

Here is an example of how your program should work. January 1, 1970, lands on a Thursday, and the week is shown ending on a Sunday.

Enter a year (0 to quit): 1970

January
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

February
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28

March
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

April
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

May
             1  2  3
 4  5  6  7  8  9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

June
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30

July
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

August
                1  2
 3  4  5  6  7  8  9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

September
    1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

October
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

November
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30

December
    1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26
28 29 30 31

The solar year is approximately 365.24219 days, and as a result of the progression of leap years, Gregorian calendar has 365.2425 days, yielding a relative error of 0.000084% per year.

A more ideal solar calendar

As an aside, rather than excluding three leap years every 400 years, a more accurate calendar would see one leap year removed every 128 years. This would yield an average year of $365.25 - \frac{1}{128} = 365.2421875$ days, which is significantly closer to the actual solar year than the Gregorian calendar, having a relative error of less than 0.00000069%, a factor of approximately 122 better.

It is a curiosity that 128 is not only divisible by four but also a power of two.