Month calender in plain C

Discussion in 'C' started by shabbir, Apr 29, 2007.

  1. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    Program prints the month without using any system related information but just making some simple calculations of days from the reference day 1/1/1900 as Monday.
    Code:
    #include<stdio.h>
    #include<conio.h>
    #define Y 1900             /*1/1/1900 Monday*/
    
    void days(int ,int );
    void display(int , int );
    
    // Almost constant but we modify the month[1] i.e. Feb for leap year
    int month[]={{31},{28},{31},{30},{31},{30},{31},{31},{30},{31},{30},{31}};
    
    int main()
    {
    	int m,yr;
    	int i = 0;
    	do
    	{
    		i++;
    		if(i > 1)
    		{
    			printf("\nWhat kind of month that was please re-enter\n");
    		}
    		printf("Enter the month [1-12]\t");
    		scanf("%ld",&m);
    	}while(m>12 || m<0);
    	i = 0;
    	do
    	{
    		i++;
    		if(i > 1)
    		{
    			printf("\nPlease enter year of this century i.e. 1900 or above\n");
    		}
    		printf("Enter the year\t");
    		scanf("%ld",&yr);
    	}while(yr<1900);
    
    	if((yr%4==0)&&((yr%100!=0)||(yr%400==0)))
    	{
    		// We did not had the month as const because of this.
    		month[1]=29;
    	}
    
    	days(m,yr);
    	printf("\n\n");
    	return 0;
    }
    
    void days(int m,int yr)
    {
    	int i,md=0,leap=0,track;
    	unsigned int d,yrd;
    	for(i=Y;i<yr;i++)
    	{
    		if((i%4==0)&&((i%100!=0)||(i%400==0)))
    			leap++;
    	}
    	for(i=0;i<(m-1)&&(i<11);i++)
    		md=md+month[i];
    	yrd=(yr-Y)*365;
    	d=yrd+leap+md;
    	track=d%7;
    	display(m,track);
    }
    
    void display(int m, int track)
    {
    	int dt,loop;
    	printf("\n\n\t");
    	printf("Mon\tTues\tWed\tThurs\tFri\tSat\tSun\n\n");
    	for(loop=0;loop<=track;loop++) 
    		printf("\t");
    	for(dt=1;dt<=month[m-1];dt++)
    	{
    		if(track%7==0 && track!=0)
    			printf("\n\n\t");
    		printf("%d\t",dt);
    		track++;
    	}
    }
    Output
    Code:
    Enter the month [1-12]  4
    Enter the year  2007
    
    
        Mon     Tues    Wed     Thurs   Fri     Sat     Sun
    
                                                        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
     
    1 person likes this.

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice