🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C Leap Year and Weekday
Write a day of week program in C with leap year logic and validation. Free C tutorial for embedded systems.
This lesson of our free C programming course builds a complete day of week program in C. You type a date such as 15/08/1947 and the program prints Friday. Along the way you learn the Gregorian leap year rule, how to stack case labels, and how a short arithmetic formula replaces a whole calendar. These are the same skills used when writing RTC firmware in embedded C programming.
Everything here is written from scratch and tested, so you can compile it and verify each result against a real calendar.
What You Will Learn
- The exact leap year rule and how to code it in one expression
- How to validate a date, including February in leap and normal years
- How stacked case labels share one body
- Why a weekday formula using year, day of year and leap day counts works
- How to map the result to a day name with a const array
- How to test the program on dates you can verify
Prerequisites
- The day of year program from the previous lecture
- Logical operators
&&,||and the%operator - Functions that return
const char *
The Leap Year Rule in C
A normal year has 365 days and a leap year has 366. The rule has three layers. A year divisible by 4 is a leap year, except when it is divisible by 100, unless it is also divisible by 400. So 2024 is leap, 1900 is not, and 2000 is. In C this becomes a single expression, and the precedence of && over || means the brackets are optional, though we keep them for readability.
static int is_leap(int y)
{
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
Read the rows in order and stop at the first match. That ordered reading is the easiest way to remember why 2000 is leap but 2100 is not.
| Year | Divisible by 4 | Divisible by 100 | Divisible by 400 | Leap? |
|---|---|---|---|---|
| 2024 | Yes | No | No | Yes |
| 2026 | No | No | No | No |
| 1900 | Yes | Yes | No | No |
| 2000 | Yes | Yes | Yes | Yes |
| 2100 | Yes | Yes | No | No |
Validating the Date with Stacked Cases
Before we compute anything, the program must reject dates like 31/04/2024. The helper month_length() returns the number of days in a month. Notice that case 4: case 6: case 9: case 11: sit one after another with nothing between them. That is fall-through with empty bodies, and it lets four months share a single return 30. February asks is_leap(), and everything else gets 31 from default.
Finding the Weekday from Day of Year
Now for the key idea. A normal year is 365 days, which is exactly 52 weeks plus 1 day. So every normal year pushes the weekday of any given date forward by one. Each leap day adds another day. If we count the leap days that happened before year y and add the day of year, the total modulo 7 tells us where we are in the week.
Using p = y - 1, the number of leap days before year y is p/4 - p/100 + p/400, using integer division. The formula is then:
index = (y + j + p/4 - p/100 + p/400) % 7
where j is the day of year, including the leap day if the date is after February. The result is an index into the names array, with 0 meaning Saturday, because the first day of the Gregorian calendar, 1 January of year 1, was a Monday and this offset lines the numbers up.
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| Day | Saturday | Sunday | Monday | Tuesday | Wednesday | Thursday | Friday |
Worked example: 15 August 1947
| Value | Result |
|---|---|
| y | 1947 |
| j (day of year, not leap) | 227 |
| p = y – 1 | 1946 |
| p/4, p/100, p/400 | 486, 19, 4 |
| Sum: 1947 + 227 + 486 – 19 + 4 | 2645 |
| 2645 % 7 | 6 → Friday |
Complete Day of Week Program in C
#include <stdio.h>
static int is_leap(int y)
{
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
static int month_length(int m, int y)
{
switch (m) {
case 4: case 6: case 9: case 11:
return 30;
case 2:
return is_leap(y) ? 29 : 28;
default:
return 31;
}
}
static int day_of_year(int d, int m, int y)
{
int total = d;
switch (m) {
case 12: total += 30;
/* fall through */
case 11: total += 31;
/* fall through */
case 10: total += 30;
/* fall through */
case 9: total += 31;
/* fall through */
case 8: total += 31;
/* fall through */
case 7: total += 30;
/* fall through */
case 6: total += 31;
/* fall through */
case 5: total += 30;
/* fall through */
case 4: total += 31;
/* fall through */
case 3: total += 28;
/* fall through */
case 2: total += 31;
/* fall through */
default: break;
}
if (m > 2 && is_leap(y))
total += 1;
return total;
}
static const char *weekday_name(int d, int m, int y)
{
static const char *names[7] = {
"Saturday", "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday"
};
int j = day_of_year(d, m, y);
int p = y - 1;
int idx = (y + j + p / 4 - p / 100 + p / 400) % 7;
return names[idx];
}
int main(void)
{
int d, m, y;
printf("Enter date (dd/mm/yyyy): ");
if (scanf("%d/%d/%d", &d, &m, &y) != 3) {
printf("Bad format\n");
return 1;
}
if (y < 1 || m < 1 || m > 12 || d < 1 || d > month_length(m, y)) {
printf("Not a valid date\n");
return 1;
}
printf("Day of year : %d\n", day_of_year(d, m, y));
printf("Weekday : %s\n", weekday_name(d, m, y));
return 0;
}
What each part does
day_of_year()uses the descending switch from the last lecture, then adds one day if the date is after February in a leap year.weekday_name()applies the formula and returns a string from a static const array. Returning a pointer to a string literal is safe because literals live for the whole program.main()readsdd/mm/yyyywith a format that includes the slashes, checks every field, and prints both results.- Each failed check prints a message and returns 1, so scripts can detect bad input.
Build and run
gcc -Wall -Wextra -std=c11 -o weekday weekday.c
./weekday
Expected output for four dates you can verify on any calendar:
Enter date (dd/mm/yyyy): 02/05/2002
Day of year : 122
Weekday : Thursday
Enter date (dd/mm/yyyy): 15/08/1947
Day of year : 227
Weekday : Friday
Enter date (dd/mm/yyyy): 29/02/2024
Day of year : 60
Weekday : Thursday
Enter date (dd/mm/yyyy): 01/01/2000
Day of year : 1
Weekday : Saturday
And an invalid date:
Enter date (dd/mm/yyyy): 31/04/2024
Not a valid date
Check yourself
Run the program for today, 23/10/2026. It should report day 296 and Friday. If it does not, recheck the case values for the months after September.
Real-World Applications
- RTC chips often store only year, month and day, so firmware computes the weekday itself.
- Schedulers for lighting, HVAC and irrigation that run different programs on weekdays and weekends.
- Smart meters and loggers that stamp records with calendar information.
- Test tools that generate dated files and need to verify the day names.
Limits of this formula
The formula assumes the Gregorian calendar throughout. Countries switched from the Julian calendar at different times, so very old dates may not match historical records. For any modern device date it is correct.
Common Mistakes and Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Dates after February off by one in leap years | Leap day not added to the day of year | Add 1 when m is greater than 2 and the year is leap |
| Century years wrong | Missing the 100 and 400 parts | Use the full three-layer rule |
| Weekday shifted by one | Used y instead of y – 1 in the leap counts | Define p = y – 1 first |
| scanf returns 1 or 2 | Typed 02-05-2002 instead of using slashes | Match the separators in the format string |
Warning
Always check the return value of scanf. Ignoring it leaves the variables uninitialised, which is undefined behaviour in C and a classic source of firmware bugs.
Best Practices
- Put the leap year rule in one helper and call it everywhere.
- Validate before calculating, so formulas never see impossible dates.
- Test century boundaries such as 1900, 2000 and 2100.
- Return const strings, not buffers, when the text never changes.
- Compare against a trusted calendar for at least five known dates.
Security and robustness
Dates that arrive from a network or sensor are untrusted input. Range checks protect the array index from overflow, which would otherwise read outside the names table.
Summary and Key Takeaways
- Leap years follow the 4, 100, 400 rule.
- Stacked case labels let months share one result.
- Weekday equals the sum of year, day of year and leap day count, modulo 7.
- Validate first, calculate second.
- Verify with dates you know from a calendar.
Conclusion
A few lines of integer arithmetic replaced an entire calendar lookup, and the switch statement gave us the day count. In the next lecture of this free embedded C course we move from dates to digits and solve the triad numbers problem, which teaches digit extraction, bit flags and a careful use of goto.
Frequently Asked Questions
How do you find the day of the week in C?
Compute the day of year, add the year and the number of leap days before it, take the sum modulo 7 and look the result up in an array of day names.
What is the leap year rule in C?
A year is leap if it is divisible by 4 and not by 100, or if it is divisible by 400.
Why is the index 0 mapped to Saturday?
The formula counts days from the first of January of year 1, which was a Monday, and that offset makes index 0 correspond to Saturday.
Can this formula run on a microcontroller?
Yes. It uses only integer addition and division, so it needs no floating point and very little code space.
Why do century years like 1900 fail the leap test?
They are divisible by 100 but not by 400, so they are not leap years.
What does stacking case labels do?
It lets several values share one block of code, because each empty label falls through to the next.
Is the formula valid for any date?
It is valid for the Gregorian calendar, so very old dates in places that used another calendar may differ.
Practice task
Write a loop that prints the weekday of the first of every month in 2026, then check three of them on a calendar.
Build Real Skills in Embedded C
Take the next step in our free C tutorial and learn digit tricks with the triad numbers problem.

2 Comments