Calendar
#include <stdio.h> // calendar.c written by martin for 59.102 July 1999 // verson 1.0 int leapyear(int year) { // is year a leap year? // the rule for leap years is that a year is a leap year if it // is divisible by four but not by 100 or it is divisible by 400 if(((year%4==0) && (year%100!=0)) || (year%400==0)) return 1; else return 0; } int daysinmonth(int year, int month) { // Thirty days hath September, April, June, and November; // All the rest have thirty-one // Excepting February alone: Which hath but twenty-eight, in fine, // Till leap year gives it twenty-nine. int monthlengths[]={31,28,31,30,31,30,31,31,30,31,30,31}; if ((month==1) && leapyear(year)) return 29; else return monthlengths[month]; } int printmonth(int year, int month, int firstday) { // print a complete month, firstday is // the number for the first day of the month (0 is sunday) char *monthnames[]={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}; int i; printf("\n %s\n",monthnames[month]); printf(" Sun Mon Tue Wed Thu Fri Sat\n"); for(i=0;i<firstday;i++) printf(" "); // print gaps at start of first week for(i=1;i<=daysinmonth(year,month);i++) { printf("%4d",i); // print the day number if((i+firstday)%7==0) // new line at the end of a week printf("\n"); } printf("\n"); return (firstday+i-1)%7; // return first day of next month } int main() { // print a calendar for a given year int i; int day; int year=1989; // work out what day of the week the first day of the year is. // Find the number of days since the start of year 1, // this is 365*(year-1) + no of leap years. // 1/1/0001 would have been a monday, so add 1. day=((year-1)*365+(year-1)/4+(year-1)/400-(year-1)/100+1)%7; for(i=0;i<12;i++) day=printmonth(year,i,day); // print each month return(0); // return success code }