Q: Given a date, we have to find out the day of the week.
Solution:
1) C = 2(3-(cent%4))
where cent = first 2 digits of the century
2) y = year + floor(year/4)
where year = last two digits of the year given
3)m = choose from the table
Month | Value |
---|---|
January | 0(leap year-3) |
Febuary | 3(leap year-6) |
March | 3 |
April | 6 |
May | 1 |
June | 4 |
July | 6 |
August | 2 |
September | 5 |
October | 0 |
November | 3 |
December | 5 |
4)sum = c + y + m + date given
5)val = sum%7
6) sun - 0,mon-1,tue-2,... sat - 6, use value and find the day
Sample program:
#include
int leapyearMonValue[] = {0,3,3,6,1,4,6,2,5,0,3,5};
int nonleapyearMonValue[] = {3,6,3,6,1,4,6,2,5,0,3,5};
void calculateDay(int date,int mon,int year)
{
int val,cent,monval,yr,i=3,temp,leapyear=0;
int splitcent[4],wrongInput=0;
if(year%4 == 0)
leapyear = 1;
if(mon>12 || mon <1)
wrongInput = 1;
if(date==30 && !(mon%2) || mon==7 || mon==1)
wrongInput = 1;
if(mon==2 && date>28 && !leapyear)
wrongInput = 1;
if(!wrongInput)
{
while(year)
{
splitcent[i--] = year%10;
year = year/10;
}
temp = splitcent[0]*10 + splitcent[1];
cent = 2*(3-(temp%4));
temp = splitcent[2]*10 + splitcent[3];
yr = temp + floor(temp/4);
if(leapyear)
monval = leapyearMonValue[mon-1];
else
monval = nonleapyearMonValue[mon-1];
val = cent + yr + monval + date;
val = val%7;
switch(val)
{
case 0:
{
printf("day is Sunday\n");
break;
}
case 1:
{
printf("day is Monday\n");
break;
}
case 2:
{
printf("day is Tuesday\n");
break;
}
case 3:
{
printf("day is Wednesday\n");
break;
}
case 4:
{
printf("day is Thursday\n");
break;
}
case 5:
{
printf("day is Friday\n");
break;
}
case 6:
{
printf("day is Saturday\n");
break;
}
default:
printf("wrong calculation\n");
}
}
else
printf("wrong Input... check the date, mon \n");
}
int main()
{
int date,mon,year;
printf("Enter the date in format DD/MM/YYYY\t eg: 14/11/2007\n");
scanf("%d/%d/%d",&date,&mon,&year);
calculateDay(date,mon,year);
getch();
return 0;
}
Wikipedia
No comments:
Post a Comment