basics · intermediate · ~20 min

Day of week via Zeller's congruence

Apply a closed-form formula with several branching cases.

Challenge

Implement int day_of_week(int y, int m, int d) returning the day of the week (0=Saturday, 1=Sunday, … 6=Friday) for the Gregorian date (y, m, d). Use Zeller's congruence.

Zeller (Gregorian): treat January and February as months 13 and 14 of the previous year; then h = (d + (13*(m+1))/5 + K + K/4 + J/4 - 2*J) mod 7 where K = y mod 100, J = y / 100.

Why this matters

Calendar arithmetic shows up in log timestamps, scheduling, and security policies. Zeller's congruence is a clean way to teach modular branching.

Input format

Gregorian date (y, m, d).

Output format

0..6.

Constraints

No system calls; pure arithmetic.

Starter code

int day_of_week(int y, int m, int d) { /* TODO */ return 0; }

Common mistakes

Forgetting the Jan/Feb shift. Mishandling negative modulo (C99: (-1) % 7 == -1).

Edge cases to handle

Jan/Feb (shift), year 2000 (boundary), pre-Gregorian years (formula doesn't apply).

Complexity

O(1).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.