C Program to find day of birth from DOB

Problem Statement

Write a C Program to find the day of birth when date of birth is given. For example, if we give 02/04/2107  (02nd April 2017) as input, the program should output that it was a Sunday.

Solution

  1. Pick a year as base year where January 1st falls on a Monday. We are using 1900 as base year in our program.
  2. Then we find the number of years after base year. Day of the week in the beginning of the year shifts by 1 in every non leap year. 365 days -> 52 * 7 + 1. 
  3. Once we know on what day a given year started, we can calculate each month’s starting day.
  4. From there it’s as simple as counting the days and finding which day it is.

In this program we find the day of birth like Monday, Sunday.. when date of birth is given. For a more detailed explanation of the method can be found here Converting a Month-Date-Year to the Day of the Week

The Program

#include<stdio.h>
#include<stdlib.h>
int main() {
int d, m, y, year, month, day, i;
printf("Enter date of birth (DD MM YYYY) :");
scanf("%d %d %d", &d, &m, &y);
if( (d > 31) || (m > 12) || (y < 1900 || y >= 2100) )
{
printf("INVALID INPUT. Please enter a valid date between 1900 and 2100");
exit(0);
}
year = y-1900;
year = year/4;
year = year+y-1900;
switch(m)
{
case 1:
case 10:
month = 1;
break;
case 2:
case 3:
case 11:
month = 4;
break;
case 7:
case 4:
month = 0;
break;
case 5:
month = 2;
break;
case 6:
month = 5;
break;
case 8:
month = 3;
break;
case 9:
case 12:
month = 6;
break;
}
year = year + month;
year = year + d;
/* Need to make sure extra day is not needed in leap year for dates before March */
if(( y > 1900 ) && ( y % 4 == 0 ) && ( m < 2 ) )
year--;
day = year % 7;
switch(day)
{
case 0:
printf("Day is SATURDAY\n");
break;
case 1:
printf("Day is SUNDAY\n");
break;
case 2:
printf("Day is MONDAY\n");
break;
case 3:
printf("Day is TUESDAY\n");
break;
case 4:
printf("Day is WEDNESDAY\n");
break;
case 5:
printf("Day is THURSDAY\n");
break;
case 6:
printf("Day is FRIDAY\n");
break;
}
return 0;
}
view raw day_of_birth.c hosted with ❤ by GitHub

Sample Output

Date of birth to day of birth
Finding day of birth from DOB

Like to get updates right inside your feed reader? Grab our feed!

To browse more C Programs visit this List of C Programs

(c) www.c-program-example.com

Leave a Reply