Está en la página 1de 17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

11,932,402 members 47,444 online

articles

Q&A

forums

Sign in

lounge

Searchforarticles,questions,tips

Calendar using C Programming language


Debabrata_Das, 8 Jun 2014

CPOL

Rate this:

4.78 21 votes
C program to display calendar of any given month and year mmyyyy

Download Calendar.zip 2.1 KB

Introduction
Like many, I also started computer programming with C language which is one of the most widely used programming
languages of all time.
In this article I'll explain a C program which accepts any monthyear and displays calendar of that month. We'll add more
features like, if user press:
Leftarrow key go to the previous month.
Rightarrow key go to the next month.
Uparrow key go to the next year.
Downarrow key go to the previous year.
I insert new month year.
P print the month in a text file.
Esc exit the program.
This simple example would be helpful for beginners as well as intermediate developers to understand some of the basic
concepts, like, declaring arrays, using functions, looping, using goto statement, printing output file, handling key press, etc.
Please feel free to share your comments / suggestions and rate this article.

Background
We will start the program by showing an input screen to the user where it will accept a month and a year in mmyyyy
format as shown below:

http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

1/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

Once user enters a valid monthyear and hits Enter key, it should display the calendar of the entered month as shown
below:

http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

2/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

If user press Leftarrow key, it will show the previous month i.e. May 2014 calendar as follows:

http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

3/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

Similarly if user press Rightarrow key, it will show the next month i.e. July 2014 on the screen:

http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

4/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

Once user hits Uparrow key, it will show month of the next year i.e. June 2015 on screen:

http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

5/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

If user hits downarrow, it will show the month of the previous year i.e. June 2013 on screen:

http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

6/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

If user press I key, it will bring the user input screen and ask for another monthyear input.
If P is pressed, it will export the month details in a textfile with file name as "JUN2014.txt" as follows:

Once user press Esc key, program will be closed.


http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

7/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

Note: I have used Turbo C++ / C compiler to create this program. Please visit the following link to download the same:
Turbo C++ / C compiler for windows xp / 7 / 8 / 8.1

Using the code


Let's start creating the input screen first in main function:
Hide Copy Code

textcolor(WHITE);
clrscr();
printf("\n\tThisprogramshowscalendarof\n");
printf("\n\tagivenmonth.Entermonth,year...formatismmyyyy.\n");
Code Explanation:
textcolor function is used to change the color of drawing text in c programs.
Declaration : void textcolorint color;
where color is an integer variable. For example 0 means BLACK color, 1 means BLUE, 2 means GREEN and soon. You can also
use write appropriate color instead of integer. For example you can write textcolorYELLOW; to change text color to YELLOW.
But use colors in capital letters only.
clrscr function is used to clear screen.
The next two lines are simply used to show the message on the console output.
Hide Copy Code

/*takinginput*/
while(TRUE)
{
fflush(stdin);
printf("\n\n\tEntermmyyyy:");
scanf("%d%d",&Month,&Year);
if(Year<0)
{
printf("\nInvalidyearvalue...");
continue;
}
if(Year<100)
Year+=1900;
if(Year<1582||Year>4902)
{
printf("\nInvalidyearvalue...");
continue;
}
if(Month<1||Month>12)
{
printf("\nInvalidmonthvalue...");
continue;
}
break;
}/*Endofwhileloop*/
Code Explanation:
Here we started with a whileTRUE loop which is an infinite loop hence you have to break the loop explicitly. Otherwise it will
continue looping infinitely. The reason behind this loop is to make sure that we accept valid input from the user. If the user
input is not valid, show an error message and prompt for input again.
http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

8/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

Hide Copy Code

fflush(stdin);
printf("\n\n\tEntermmyyyy:");
scanf("%d%d",&Month,&Year);
fflushstdin; This function is called to clear the input buffer.
The other lines are used to accept user input in two variables, Month and Year.
Hide Copy Code

if(Year<0)
{
printf("\nInvalidyearvalue...");
continue;
}
if(Year<100)
Year+=1900;
if(Year<1582||Year>4902)
{
printf("\nInvalidyearvalue...");
continue;
}
if(Month<1||Month>12)
{
printf("\nInvalidmonthvalue...");
continue;
}
break;
We have written some code for data validation, like year should be greater than 0. In case user enters year in yy format like, 98,
it will add 1900 to make it as 1998. The program will accept a range of years from 1952 to 4902. Any year entered beyond this
range will not be accepted as a valid year.
Month has to be within the range of 1 to 12. Any input beyond this range will not accepted as a valid month.
If none of the conditions met, break; statement will be executed and program flow will proceed.
Note: Afer every validation failure message continue; statement is written to make sure that the rest of the codes within the
loop are not executed.
Before we proceed with the remaining part of the main method, let's declare some constant and write the required functions.
Hide Copy Code

#defineLEAP_YEAR((Year%4==0&&Year%100!=0)||Year%400==0)
#defineTRUE1
#defineCH''
#defineMAX_NO91
#define directive is used to define a constant or creating a macro in C programming language. The first statement is defining a
macro which accepts Year as an input parameter and returns TRUE/FALSE. If the year is a Leap Year, it returns TRUE otherwise
FALSE.
The other three lines are used to define constants.
Hide Copy Code

intMonthDay[]={31,28,31,30,31,30,31,31,30,31,30,31};
char*MonthName[]={"January","February","March","April","May","June","July",
"August","September","October","November","Decembeer"};
char*MonthName1[]={"JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP",
"OCT","NOV","DEC"};
http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

9/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

Here wehave declared three arrays. MonthDay[] will be used to determine the number of days in a month. We will handle Leap
Year separately. *MonthName[] and*MonthName1[] are array of strings.
Note: Array of strings can be declared in two ways:
char array[ROW][COL]; where you know the number of rows, ROW and number of columns, COL.
char *array[ROW]; in this way, you have to provide number of rows only. If you initialize the array with values at the
time of declaration, ROW number becomes optional.
In our case, we have not provided number of rows as we have initialized the array with values at the time of declaration only.
Let's move on to add the required functions:
Hide Copy Code

/*================FUNCTIONTOCALCULATEZELLER'SALGORITHM=============*/
intgetZeller(intMonth,intYear)
{
intDay=1,ZMonth,ZYear,Zeller;
if(Month<3)
ZMonth=Month+10;
else
ZMonth=Month2;
if(ZMonth>10)
ZYear=Year1;
else
ZYear=Year;
Zeller=((int)((13*ZMonth1)/5)+Day+ZYear%100+
(int)((ZYear%100)/4)2*(int)(ZYear/100)+
(int)(ZYear/400)+77)%7;
returnZeller;
}
Zeller's Algorithm can be used to determine the day of the week for any date in the past, present or future, for any dates
between 1582 and 4902. We're using this function to get the weekday of the 1st day of given month.
Hide Copy Code

/*====================FUNCTIONTOGETKEYCODE=========================*/
getkey()
{
unionREGSi,o;
while(!kbhit())
;
i.h.ah=0;
int86(22,&i,&o);
return(o.h.ah);
}
kbhit a function returns integer value whenever the key is pressed by the user. We'll be using this function to catch user
input, like, leftarrow key, rightarrowkey, uparrow key, downarrow key, I, P, etc.
Hide Copy Code

voidprintchar(charc)
{
inti;
printf("\n\t");
for(i=1;i<=51;i++)
printf("%c",c);
printf("\n");
}
printchar; It accepts a character and prints the same 51 times on a single line. This function will be used to do some
formatting the output.
http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

10/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

Hide Shrink

Copy Code

voidPrintFile(intM,intY,intZ)
{
inti,j;
charfilename[12];
charstryear[5];
FILE*stream;
strcpy(filename,MonthName1[M1]);
itoa(Y,stryear,10);
strcat(filename,stryear);
strcat(filename,".txt");
if((stream=fopen(filename,"w"))==NULL)
{
printf("\nErrorcannotcreatefile.");
getch();
exit(1);
}
fprintf(stream,"\n\t\t\t%s%d\n\n\t",MonthName[M1],Y);
for(i=1;i<=MAX_NO;i++)
fprintf(stream,"");
fprintf(stream,"\n\tSUN\tMON\tTUE\tWED\tTHU\tFRI\tSAT\n\t");
for(i=1;i<=MAX_NO;i++)
fprintf(stream,"");
/*settingstartingposition*/
fprintf(stream,"\n");
for(i=1;i<=Z;i++)
fprintf(stream,"\t");
j=Z;
/*printingdates*/
for(i=1;i<=MonthDay[M1];i++)
{
if(j++%7==0)
fprintf(stream,"\n");
fprintf(stream,"\t%2d",i);
}
fprintf(stream,"\n\t");
for(i=1;i<=MAX_NO;i++)
fprintf(stream,"");
fprintf(stream,"\n\n\t\tCreatedby:DebabrataDas[debabrata.dd@gmail.com]");
fclose(stream);
}
Code Explanation:
PrintFile; function will be used to print the output in a text file and save in the disk.
Hide Copy Code

inti,j;
charfilename[12];
charstryear[5];
FILE*stream;

http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

11/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

Variable declaration section where we declared two integer variables i, j, two character array filename, stryear and a FILE
pointer which is used to communicate with file in C language.
Hide Copy Code

strcpy(filename,MonthName1[M1]);
itoa(Y,stryear,10);
strcat(filename,stryear);
strcat(filename,".txt");
strcpydes, src; this function is used to copy src string to the des string. Here month name will be copied to filename
variable. The month name will be used to create the text file name.
itoa; is used to convert an integer to a string. We're converting given year to string so that it can be concatenated with the
month name and form the output text file name.
strcatstr1, str2; this function is used to concatenate str2 with str1. Initially we copied the month name in filename variable.
Now we concatenate year with the month name to make the filename as follows: "JUN2014"
we have used strcat again to append ".txt" extension of the file. Finally the filename will hold a complete file name as follows:
"JUN2014.txt"
Hide Copy Code

if((stream=fopen(filename,"w"))==NULL)
{
printf("\nErrorcannotcreatefile.");
getch();
exit(1);
}
The above code will try to open the file in writeonly mode "w". If it fails to open the file due to any reason, fopen function
will return a NULL value. Then we can display a message that "Errorcannot create file."
getch; this function is used to get a character/key hit from the console input i.e. keyboard. Program waits until the user hits
any key on the keyboard.
exit1; will exit from the program.
Hide Copy Code

fprintf(stream,"\n\t\t\t%s%d\n\n\t",MonthName[M1],Y);
for(i=1;i<=MAX_NO;i++)
fprintf(stream,"");
fprintf(stream,"\n\tSUN\tMON\tTUE\tWED\tTHU\tFRI\tSAT\n\t");
for(i=1;i<=MAX_NO;i++)
fprintf(stream,"");
/*settingstartingposition*/
fprintf(stream,"\n");
for(i=1;i<=Z;i++)
fprintf(stream,"\t");
j=Z;
/*printingdates*/
for(i=1;i<=MonthDay[M1];i++)
{
if(j++%7==0)
fprintf(stream,"\n");
fprintf(stream,"\t%2d",i);
}
fprintf(stream,"\n\t");
for(i=1;i<=MAX_NO;i++)
fprintf(stream,"");
fprintf(stream,"\n\n\t\tCreatedby:DebabrataDas[debabrata.dd@gmail.com]");
http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

12/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

The above lines are used to print the dates of the month with proper formating.
Hide Copy Code

fclose(stream);
Once everything is written to the file, fclose function is called to close the file properly.
Now we're done with all the required functions. Let's complete the logic in main method.
Hide Shrink

Copy Code

do
{
/*calculatingdayof1stdateofgivenmonth*/
Zeller=getZeller(Month,Year);
clrscr();
printf("\n\n\t\t\t");
/*printingthecorrespondingmonthname*/
textbackground(Month);
cprintf("%s%d\n",MonthName[Month1],Year);
textbackground(BLACK);
/*adjustingFebruaryincaseofLeapYear*/
MonthDay[1]=LEAP_YEAR?29:28;
/*givingoutput*/
printchar(CH);
textcolor(12);/*LIGHTRED*/
printf("\t");cprintf("SUN");
textcolor(LIGHTGREEN);
cprintf("MONTUEWEDTHUFRISAT");
textcolor(7);
printchar(CH);
/*settingstartingposition*/
for(i=1;i<=Zeller;i++)
printf("\t");
j=Zeller;
/*printingdates*/
for(i=1;i<=MonthDay[Month1];i++)
{
if(j++%7==0)
{
printf("\n\t");
textcolor(12);
cprintf("%2d",i);
textcolor(WHITE);
}
else
printf("%2d",i);
}
printchar(CH);
printf("\n\n\t\t(*)UseLeft,Right,Up&DownArrow.");
printf("\n\n\t\t(*)PressIforNewMonth&Year.");
printf("\n\n\t\t(*)PressPforPrinttoFile.");
printf("\n\n\t\t(*)PressESCforExit.\n\n\n\t\t");
textcolor(11);
textbackground(9);
cprintf("Createdby:DebabrataDas[debabrata.dd@gmail.com]");
textcolor(WHITE);
http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

13/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

textbackground(BLACK);
KeyCode=getkey();/*gettingKeyCode*/
if(KeyCode==72)/*UpArrow*/
Year++;
if(KeyCode==80)/*DownArrow*/
Year;
if(KeyCode==77)/*RightArrow*/
{
Month++;
if(Month>12)
{
Month=1;
Year++;
}
}
if(KeyCode==75)/*LeftArrow*/
{
Month;
if(Month<1)
{
Month=12;
Year;
}
}
if(KeyCode==25)/*CodeofP*/
PrintFile(Month,Year,Zeller);
if(KeyCode==23)/*CodeofI*/
gotoTop;
}while(KeyCode!=1);/*Endofdowhileloop*/
Code Explanation:
textbackground; This function is used to change current background colour in text mode.
Hide Copy Code

/*adjustingFebruaryincaseofLeapYear*/
MonthDay[1]=LEAP_YEAR?29:28;
As we mentioned earlier, here we are calculating the days in February month. If it's a leap year, consider 29 days else 28 days.
Rest of the codes are very straight forward hence not explaining each and every lines of code.
Let's compile and execute the program. Hope you like this article. Please leave your comment/suggestion and don't forget to
rate.
Happy coding

History

Keep a running update of any changes or improvements you've made here.

License
http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

14/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

This article, along with any associated source code and files, is licensed under The Code Project Open License CPOL

Share
EMAIL

TWITTER

About the Author


Debabrata_Das
Architect
India

My name is Debabrata Das, also known as DD. I started working as a FoxPro 2.6 developer then gradually moved towards
VB6, Classic ASP, COM, DCOM. Presently in love with ASP.NET and C#.
I believe in "the best way to learn is to teach". Passionate about finding a more efficient solution of any given problem.

You may also be interested in...


Calendar

Embedding Analytics into a


Database Using JMSL

Jalali Calendar

SAPrefs - Netscape-like
Preferences Dialog

Tray Calendar

WPF Localization Using RESX


Files

http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

15/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

Comments and Discussions

You must Sign In to use this message board.


Search Comments

Go
First Prev Next

calendar
Member 11681197
Re: calendar
Debabrata_Das
Error
Member 11566505
Re: Error
Debabrata_Das
nice article
Member 11421993
Re: nice article
Debabrata_Das
Nice Article
Manikandan10

11May15 3:33
14May15 7:00
30Mar15 1:56
30Mar15 4:26
2Feb15 16:13
2Feb15 20:36

10Jun14 22:44

Re: Nice Article


Debabrata_Das

10Jun14 22:46

My vote of 5
cghao 10Jun14 22:33
Re: My vote of 5
Debabrata_Das

10Jun14 22:41

Nice Calendar program


andreas proteus 10Jun14 5:17
It would be nice, however, if it was more up date using Win32 API rather than the old int86 DOS calls.
Sign In ViewThread Permalink

Re: Nice Calendar program


Debabrata_Das 10Jun14 5:28
Re: Nice Calendar program
http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx
andreas proteus 10Jun14 10:09

16/17

30/11/2015

CalendarusingCProgramminglanguageCodeProject

andreas proteus

10Jun14 10:09

Re: Nice Calendar program


Debabrata_Das 11Jun14 19:30
My vote of 5
Sharjith 10Jun14 2:44
Re: My vote of 5
Debabrata_Das
Nice article
suhel_khan

10Jun14 3:08

8Jun14 21:31

Re: Nice article


Debabrata_Das

8Jun14 21:46

Refresh
General

News

1
Suggestion

Question

Bug

Answer

Joke

Praise

Rant

Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.151126.1 | Last Updated 8 Jun 2014

Seleccionar idioma

Layout: fixed | fluid

Article Copyright 2014 by Debabrata_Das


Everything else Copyright CodeProject, 19992015

http://www.codeproject.com/Articles/783307/CalendarusingCProgramminglanguage?msg=5058370#xx5058370xx

17/17