Pages - Menu

Monday 8 October 2012

Finding day of the year given the date in C

The following C function computes and returns the day of the year based on the date received as argument in the function call.

You can read more about the function used for checking if the given year is a leap year or not by reading this article: Leap year checking algorithm in C


You can find the function that does the opposite coversion by reading Finding date given the day of the year in C 


In order to work easily with a date, I first defined a structure consisting of two integers, day and year and a pointer to an array of characters for the month.

typedef struct
{
    int day;
    char *month;
    int year;
}date;

/*
 * Description:
 *  Computes and returns the day of the year
 * Parameters:
 *  d - the date
 * Returns:
 *  day - the corresponding day of the year
 */
int DateToDay(date *d)
{
    int noDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};//number of days of each month
    char months[][20] = {"January","February","March","April","May","June",
                           "July","August","September","October","November","December"};
    int isLeapYear = 0, day = 0, i = 0;
    isLeapYear = LeapYear(d->year);
    if(isLeapYear == 1)
    {
        noDays[1] = 29;
    }
    if(strcmp(d->month,"January") != 0)//the date is not in january
    {
        for(i=0; i<12 && strcmp(d->month,months[i]) != 0; i++)
        {
            if(i != 0 )
            {
                day += noDays[i-1];
            }
        }
        day += noDays[i-1]+d->day;
    }
    else//the date is in January
    {
        day = d->day;
    }
    return day;
}

Example:

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>

int LeapYear(int year);
int DateToDay(date *d);

int main(void)
{
    date *d;
    int day = 0, isFound = 0, i =0;
    char months[][20] = {"January","February","March","April","May","June",
                         "July","August","September","October","November","December"};
    d = (date*)malloc(sizeof(date));
    d->month = (char*)malloc(sizeof(char)*20);
    printf("\n Enter the day: "); 
    scanf("%d",&d->day);
    printf(" Enter the month: "); 
    fflush(stdin); gets(d->month);
    printf(" Enter the year: "); 
    scanf("%d",&d->year);
    for(i=0; i<12; i++)
    {
        if(strcmp(months[i],d->month) == 0)
        {
            isFound = 1;
            break;
        }
    }
    if(d->day > 0 && isFound == 1)
    {
        day = DateToDay(d);
        printf("\n\tDay of the year: %d",day);
    }
    else
    {
        printf("\n\tIncorrect date!");
    }
    getch();
    return 0;
}
Output:


1 comment:

  1. Videoslots - YouTube, Videoslots, Free Play, Bonus, Videoslots
    Videoslots - YouTube, Videoslots, Free Play, Bonus, Videoslots · Videoslots. Free youtube link to mp3 slot machines. Free demo slots · Video slots. Free demo slots.

    ReplyDelete