What is Day of Year Program in C- Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

PREV_LEC | NEXT_LEC

Free C Tutorial · Control Statements

Day of Year Program in C

Build a day of year program in C using switch fall-through and a lookup table. Free embedded C course lecture.

2
Implementations
12
Month lengths
122
Day for 2 May

In this lesson of our free C tutorial we write a day of year program in C. Given a date, it reports which day of the year that date is, for example the 2nd of May is day 122. It sounds like a calendar exercise, but the same logic runs inside real-time clock drivers, data loggers and scheduler code, which makes it a perfect topic for anyone learning C programming for embedded systems.

We reuse the fall-through idea from the previous lecture and compare it with a lookup table, so you finish with two working solutions and a feel for when each one is better.

What You Will Learn

  • What the day of year (ordinal date) means and where firmware uses it
  • How to count days with a descending switch and no break statements
  • Why the trick is easier to read than eleven long cases with hand-added sums
  • How to solve the same problem with a constant array and a for loop
  • How to compare two implementations inside one test program
  • How to handle invalid months safely

Prerequisites

  • Switch and fall-through from the previous lecture
  • Functions, static functions and return values
  • Arrays and the for loop

What Is the Day of Year?

The day of year counts days from the first of January. January 1 is day 1, February 2 is day 33 and December 31 is day 365, or 366 in a leap year. Many textbooks call this number the Julian day. Be careful with that name: astronomers use Julian Day Number for a continuous count that stretches over thousands of years. For our purpose, day of year or ordinal date is the cleaner term, and it is what you will see in log files and RTC datasheets.

To compute it, take the day of the month and add the lengths of all complete months before it. For May 2, the complete months are January, February, March and April, so the answer is 2 + 31 + 28 + 31 + 30 = 122 in a normal year.

Cumulative days before each month

MonthDays before it (non-leap)MonthDays before it (non-leap)
January0July181
February31August212
March59September243
April90October273
May120November304
June151December334

These twelve numbers are all the information the problem contains. The two approaches below simply differ in how they produce them.

Day of Year Program in C with a Switch

The idea is to enter the switch at the current month and let control fall downwards through every earlier month, adding one month length at each step. Because we want to add the previous month, case 5 adds April, case 4 adds March and so on. The cases are written from December down to January, so entering at any month executes exactly the months before it.

Entering at month 5 (May)
month = 5 enter case 5 +30 Apr
 falls to case 4 +31 Mar
 falls to case 3 +28 Feb
 falls to case 2 +31 Jan
 falls to case 1 break total = 120 

Add the day of the month (2) and you get 122. Notice that entering at month 1 hits only the final case, which does nothing and breaks, so January days stay as typed.

The complete program

#include <stdio.h>

/* Days that have passed before day 1 of 'month' in a non-leap year.
 * Descending cases with no break: jumping in at case N executes
 * every case below it too, so each case adds the PREVIOUS month. */
static int days_before_switch(int month)
{
    int total = 0;

    switch (month) {
    case 12: total += 30; /* November  */
    /* fall through */
    case 11: total += 31; /* October   */
    /* fall through */
    case 10: total += 30; /* September */
    /* fall through */
    case 9:  total += 31; /* August    */
    /* fall through */
    case 8:  total += 31; /* July      */
    /* fall through */
    case 7:  total += 30; /* June      */
    /* fall through */
    case 6:  total += 31; /* May       */
    /* fall through */
    case 5:  total += 30; /* April     */
    /* fall through */
    case 4:  total += 31; /* March     */
    /* fall through */
    case 3:  total += 28; /* February  */
    /* fall through */
    case 2:  total += 31; /* January   */
    /* fall through */
    case 1:  break;
    default: return -1;
    }
    return total;
}

/* Same job with a lookup table. */
static int days_before_table(int month)
{
    static const int len[12] = {31, 28, 31, 30, 31, 30,
                                31, 31, 30, 31, 30, 31};
    int i, total = 0;

    if (month < 1 || month > 12)
        return -1;
    for (i = 0; i < month - 1; i++)
        total += len[i];
    return total;
}

int main(void)
{
    int d, m;

    printf("Enter day and month (dd mm): ");
    if (scanf("%d %d", &d, &m) != 2) {
        printf("Bad input\n");
        return 1;
    }

    int a = days_before_switch(m);
    int b = days_before_table(m);

    if (a < 0 || b < 0) {
        printf("Month must be 1 to 12\n");
        return 1;
    }

    printf("switch version : day %d of the year\n", a + d);
    printf("table version  : day %d of the year\n", b + d);
    return 0;
}

How it works

  • days_before_switch() returns how many days passed before day 1 of the month. Anything outside 1 to 12 reaches default and returns -1, so the caller can detect bad input.
  • days_before_table() keeps the month lengths in a static const array. The loop adds the first month - 1 entries.
  • main() runs both functions on the same input. If the answers ever differ, one of them has a typing mistake.
  • February is fixed at 28 days here. We deal with leap years in the next lecture.

Build and run

gcc -Wall -Wextra -std=c11 -o doy doy.c
./doy

Expected output for the 2nd of May:

Enter day and month (dd mm): 2 5
switch version : day 122 of the year
table version  : day 122 of the year

Expected output for the last day of a normal year:

Enter day and month (dd mm): 31 12
switch version : day 365 of the year
table version  : day 365 of the year

Switch Versus Lookup Table

Both versions give identical answers. Which should you ship? The table is usually the better engineering choice: the data is in one place, it is easy to audit against a calendar, and a leap-year adjustment is a single extra line. The switch is a good learning tool because it shows exactly how fall-through behaves, and you will meet it in older code bases.

AspectDescending switchConstant array + loop
ReadabilityNeeds a comment explaining the orderSelf-explanatory
Risk of typoMonth lengths mixed with control flowData is isolated in one array
Flash and RAMCode only12 ints in flash if declared const
Compiler warningsNeeds fall-through markersNone
Extending (leap, calendars)Edit many linesChange the data or one condition
Best forTeaching fall-throughProduction firmware

Embedded tip

Declare lookup tables static const so the linker places them in flash instead of RAM. On a microcontroller with 8 KB of RAM this matters.

Real-World Uses of Day of Year

  • Real-time clock drivers that store a date and need to compute elapsed days.
  • Data loggers that name files by year and day, for example 2026_296.csv.
  • Solar and irrigation controllers that vary behaviour across the year.
  • Warranty and licence timers inside industrial devices.
  • Converting between calendar dates and the ordinal dates used in many standards.

Common Mistakes and Troubleshooting

SymptomLikely causeFix
Result off by a month lengthCase adds the current month, not the previous oneRe-check which month each case represents
Result too small for any dateA break left inside the chainRemove the break or mark it on purpose
Wrong answer for DecemberCase 12 missingCases must run from 12 down to 1
Garbage for month 0 or 13No input checkUse default to reject, or test before calling
Always same answerReading month as the dayCheck scanf argument order: day first, then month

Warning

Do not trust one passing test. Check the 1st of January, the 1st of March, the 31st of December and a mid-year date, because off-by-one mistakes hide at boundaries.

Best Practices

  1. Return a clear error value for bad input and check it at the call site.
  2. Write two independent implementations for important logic and compare them in a test.
  3. Keep tables const and name them clearly.
  4. Comment any fall-through chain with the direction in which it runs.
  5. Keep calendar code in small functions so the leap-year change in the next lecture drops in cleanly.

Performance considerations

Both versions finish in a handful of instructions. The array loop runs at most 11 iterations, and a good compiler may even unroll it. Optimise for clarity first and measure only if this runs in a time-critical interrupt, which it should not.

Summary and Key Takeaways

  • Day of year equals the day number plus all complete earlier months.
  • A descending switch without breaks adds those months automatically.
  • A constant array and loop does the same job with clearer data.
  • Validate the month, and test boundaries.
  • Leap years add one day for dates after February, which we handle next.

Conclusion

You now have two ways to compute the day of year and a reason to pick one over the other. The switch gave you hands-on practice with fall-through, and the table showed how real firmware keeps data apart from logic. Next in this free embedded C course we add the leap-year rule and use the result to find the day of the week from any date.

Frequently Asked Questions

What is the day of year?

It is the position of a date within its year, counting January 1 as day 1. December 31 is day 365 or 366.

Is day of year the same as Julian day?

Not exactly. Julian Day Number is an astronomical continuous count. The ordinal date used here is often loosely called a Julian day in textbooks.

Why does the switch run from case 12 down to case 1?

So entering at any month falls through every earlier month and adds their lengths, without needing any break.

Which is better for embedded C, switch or array?

A const array is usually cleaner and easier to verify, while the switch is mainly useful to learn fall-through.

How do I handle an invalid month?

Return an error value from the default label or check the range before the calculation, then stop.

Does this code handle leap years?

Not yet. February is fixed at 28 days here. The next lecture adds the leap-year rule.

Why use static const for the table?

It lets the compiler place the table in flash and keeps it private to the file, which saves RAM on microcontrollers.

Practice task

Add a third function that sums the lengths in a loop using a switch on the month to pick 28, 30 or 31, then compare all three results for every date of the year.

Continue Your Free Embedded C Course

Next up: the leap year rule and the day of the week. Keep going with the free C programming course on EmbeddedPathashala.

PREV_LEC | NEXT_LEC

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →