# C Program to calculate the day of year from the date

Last updated on September 24, 2020

The following is a C program to calculate the day of year from the date:

  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 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 /************************************************* Program to calculate day of year from the date * * Enter date (MM/DD/YYYY): 12/30/2006 * Day of year: 364 * ************************************************/ #include // include stdio.h library int main(void) { int day, mon, year, days_in_feb = 28, doy; // day of year printf("Enter date (MM/DD/YYYY): "); scanf("%d/%d/%d", &mon, &day, &year); doy = day; // check for leap year if( (year % 4 == 0 && year % 100 != 0 ) || (year % 400 == 0) ) { days_in_feb = 29; } switch(mon) { case 2: doy += 31; break; case 3: doy += 31+days_in_feb; break; case 4: doy += 31+days_in_feb+31; break; case 5: doy += 31+days_in_feb+31+30; break; case 6: doy += 31+days_in_feb+31+30+31; break; case 7: doy += 31+days_in_feb+31+30+31+30; break; case 8: doy += 31+days_in_feb+31+30+31+30+31; break; case 9: doy += 31+days_in_feb+31+30+31+30+31+31; break; case 10: doy += 31+days_in_feb+31+30+31+30+31+31+30; break; case 11: doy += 31+days_in_feb+31+30+31+30+31+31+30+31; break; case 12: doy += 31+days_in_feb+31+30+31+30+31+31+30+31+30; break; } printf("Day of year: %d", doy); return 0; // return 0 to operating system } 

Expected Output: 1st run:

 1 2 Enter date (MM/DD/YYYY): 03/05/2000 Day of year: 65 

2nd run:

 1 2 Enter date (MM/DD/YYYY): 12/25/2018 Day of year: 359 

## How it works #

Day of year is a number between 1 and 365 (or 366, if leap year). For example, 1st Jan is day 1, 5th Feb is day 36 and so on.

To calculate the day of year we simply add days in the given month to the days in the previous months.