67.8k views
0 votes
The UNIX cal command prints out the calendar of the month/year that the user enters. Type in the following, one at a time, and observe the output:

cal 3 2014 cal 2014 cal 1 1
To learn more about this command, type in man cal for help.
Write a program named cal.c that prints out the following (which is the output when you type in cal 10 2018 in UNIX). Note that you are not asked to implement the cal command. You can assume that you know October 1 is a Monday. You will need to use loops and the % operator.
October 2018 Su Mo Tu We Th Fr Sa 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

1 Answer

3 votes

Solution :

#include<
$\text{stdio.h}$>

int
$\text{dayofweek}$(int d,
$\text{int m}$, int y){

static
$\text{int t}[]$ = { 0,
$3,2$, 5,
$0,3$, 5, 1,
$4,6,2,4$ };

y -=
$m<3$;

return (
$y+$ y/4 - y/100 + y/400 + t[m-1] + d) % 7;

}

int main() {

int month,year,i;

printf("Enter Month : ");

scanf("%d",&month);

printf("Enter Year : ");

scanf("%d",&year);

//find week day number

int day = dayofweek(1,month,year);

char * weekDays[] = {"Su","Mo","Tu","We","Th","Fr","Sa"};

printf("\\");

//print week day header

for(i=0;i<7;i++)

printf("%s ",weekDays[i]);

printf("\\");

//print days accordingly

for(i=0;i<day;i++)

printf(" ");

for(i=day;i<=day+30;i++){

printf("%-2d ",i-day+1);

if((i+day)%7==0)

printf("\\");

}

}

User Tibtof
by
3.1k points