Skip to content
Tutorials Center
My learning

Topics

Lesson 123 of 135 ยท Projects

Project: Printing a Calendar

Print a month and a whole year calendar in C: leap-year rules, a day-of-week calculation you can verify, a month renderer that builds text lines, and a three-column year view.

Printing a calendar sounds like a beginner exercise, and the first version is, but a correct one forces you to deal with two things programmers love to get wrong: dates and text layout. Which weekday was 1 January 2000? Is 2100 a leap year? How do you print three months side by side when each month is several lines tall? None of this needs a library, and doing it by hand teaches more than calling strftime ever would.

The project uses functions, arrays, two-dimensional layouts, string formatting and reading numbers from input. It is a good follow-up to the time and date lesson, which shows the standard library's tools for the same job. Stage 1 is the date arithmetic, with a cross-check that proves it right. Stage 2 is the layout: one month, then a full year.

Stage 1: date arithmetic you can trust

Leap years. A year is a leap year if it is divisible by 4, except that years divisible by 100 are not leap years, except that years divisible by 400 are. So 2024 and 2000 are leap years, while 1900 and 2100 are not. The one-line version is (y % 4 == 0 && y % 100 != 0) || y % 400 == 0. The three-level rule is the part that gets forgotten, and the programs that forget it were correct for the whole of their authors' careers, and wrong in 2100.

Days in a month. A small table holds 31, 28, 31, 30 and so on. For February, the function adds one when is_leap is true. A table is shorter and clearer than a chain of ifs, and the month number is used as an index after subtracting one.

Counting days is simpler than a clever formula. To find the weekday of any date, count how many days have passed since a date whose weekday you know, then take the remainder by 7. In the Gregorian calendar, which our rules describe, 1 January of year 1 is a Monday. So:

  1. days_before_year(y) is the number of days in all complete years before y: 365 * (y - 1) plus one extra day for each leap year among those, which is (y-1)/4 - (y-1)/100 + (y-1)/400 (leap years counted by the same three-level rule).
  2. day_of_year(y, m, d) adds up the lengths of the months before m and then d. 1 January is day 1.
  3. The date's number is days_before_year(y) + day_of_year(y, m, d). Day 1 is a Monday, so the number modulo 7 is 1 for Monday, 2 for Tuesday, and 0 for Sunday.

That makes the result 0 for Sunday, 1 for Monday, up to 6 for Saturday, the order most calendars use when the week starts on Sunday. Every step can be checked by hand, and that is the point.

Proving it with a second method. A single method that "seems to work" is a risky thing to ship. Dates have a famous independent formula, Sakamoto's algorithm, which uses a 12-number table and a trick: for January and February, it counts them as part of the previous year, so that the leap day is always at the end of the "year". The program implements it as day_of_week_sakamoto and then compares the two methods for every day of every year from 1900 to 2100, about 73,000 dates. If they agree on all of them, both are almost certainly right, because two different derivations rarely make the same mistake. The demo also prints a few dates whose weekday you can check against any real calendar.

C Stage 1: leap years, weekdays and a cross-check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The last line is the proof. Change days_before_year so that it forgets the - p / 100 + p / 400 part and run it again: many dates become wrong and the number of mismatches jumps from 0 to thousands. A test that fails when you break the code is a test worth having.

Stage 2: laying out a month and a year

Build lines of text, then print them. The tempting way to print a month is to call printf straight away: print the title, print spaces until the first weekday, print the days, print a newline after each Saturday. That works for one month. It cannot print three months side by side, because printf writes one complete line at a time, and the second month's first line comes after the first month's last one.

The way out is to separate drawing from printing. render_month does not print anything. It fills a small array of eight lines, each exactly 20 characters wide: the title, the weekday header, and up to six rows of days. Then printing one month means printing eight lines, and printing three months side by side means printing line 0 of each month, then line 1 of each, and so on. This is a pattern that appears whenever text is composed from parts: render each part to a buffer, then combine buffers.

Placing a day. The grid cell of day d is found with one number: idx = first + d - 1, where first is the weekday of the 1st (0 for Sunday). The row is idx / 7 and the column is idx % 7. Every cell is three characters wide (two for the number, one for a space), so the day is written at character offset column * 3 of line 2 + row. Six rows are enough for any month: the longest case is a 31-day month starting on Saturday, which touches six weeks.

Padding. memset fills every line with spaces before anything is written, and the terminating '\0' is set at position 20. Then single numbers can be copied in with memcpy: no printf padding arithmetic and no risk of one line being shorter than another. The title is centered by writing it at (20 - length) / 2.

Skipping empty lines. Most months use only five rows, so line 7 is often blank for all three months in a row of the year view. The year printer asks is_blank and skips those lines, so the year does not have gaps between rows of months.

Reading the request. The program reads one line. sscanf returns how many numbers it found: with one number, it is a year and the whole year is printed. With two numbers (2 2024), they are month and year. A bad month or year gives a short usage message. The year is limited to 1 through 9999, the range in which the formulas and the four-digit layout are meaningful.

C Stage 2: one month and a whole year

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Look at February 2024 first: it has 29 days, and 1 February is a Thursday, so the number 1 sits in the fifth column. Now compare it with February in the year view. Change the input to 2 2100 for one month: February 2100 stops at 28, because 2100 is not a leap year. Try 11 2026, and check that 9 November falls on a Monday, as Stage 1 predicted.

Ideas for going further

  • Week starts on Monday. Use (weekday + 6) % 7 for the column and change the header. A macro WEEK_STARTS_ON_MONDAY is the clean way to offer both.
  • Today highlighted. Get the current date with time and localtime (see time and date) and print the day in reverse video with the ANSI code \033[7m. This changes the cell width, so decide how the buffers handle it.
  • Day-of-year and week number. Add a function for the ISO week number, which has tricky rules at the start and end of a year.
  • Holidays from a file. Read a list of month day name lines and mark those days with an asterisk.
  • Days between two dates. The date number from Stage 1 makes this one subtraction.
  • The calendar reform. Real history skipped ten days in October 1582 in some countries. Decide whether your program should model that, and for which years.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these years is a leap year?

    2000 is divisible by 400, so it is a leap year. 1900 and 2100 are divisible by 100 but not by 400, and 2023 is not divisible by 4.
  2. 2. What does days_before_year(y) add to 365 * (y - 1)?

    Every leap year before y contributes one extra day. The expression counts years divisible by 4, removes those divisible by 100, and adds back those divisible by 400.
  3. 3. Why does the Stage 1 program compare two different weekday formulas over 200 years?

    A cross-check with an independent derivation is a strong test. If one has a bug, the two disagree somewhere.
  4. 4. Why does render_month build lines of text instead of calling printf directly?

    printf writes whole lines in order. To place months side by side you need all their lines available, so each month is drawn into a buffer first.
  5. 5. In render_month, which line and offset hold day d when the 1st falls on weekday first?

    The cell number idx counts from the first cell of the grid. Dividing by 7 gives the week row and the remainder gives the column, and each column is three characters wide.

Summary

  • A year is leap when divisible by 4, except for multiples of 100 that are not multiples of 400.
  • Compute the weekday by counting days from a known date and taking the result modulo 7. Counting days is easy to check by hand.
  • Test date code against a second, independent method over a large range, and against a few dates you know.
  • Separate drawing from printing: render each month into fixed-width lines, then combine lines to print months side by side.
  • Fill buffers with memset first so every line has the same width, then write pieces at computed offsets.
  • Validate input numbers before using them as array indexes.

Next: the reservation system project, where a table of seats is saved to a binary file.