Click here to Skip to main content
15,881,172 members
Articles / Programming Languages / C

Calendar using C Programming language

Rate me:
Please Sign up or sign in to vote.
4.83/5 (24 votes)
8 Jun 2014CPOL7 min read 233K   5.4K   19   25
C program to display calendar of any given month and year (mm-yyyy)

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 month-year and displays calendar of that month. We'll add more features like, if user press:

  • Left-arrow key - go to the previous month.
  • Right-arrow key - go to the next month.
  • Up-arrow key - go to the next year.
  • Down-arrow 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 mm-yyyy format as shown below:

Image 1

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

Image 2

  • If user press Left-arrow key, it will show the previous month (i.e. May 2014) calendar as follows:

Image 3

  • Similarly if user press Right-arrow key, it will show the next month (i.e. July 2014) on the screen:

Image 4

Once user hits Up-arrow key, it will show month of the next year (i.e. June 2015) on screen:

Image 5

  • If user hits down-arrow, it will show the month of the previous year (i.e. June 2013) on screen:

Image 6

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

Image 7

  • Once user press Esc key, program will be closed.

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:

textcolor(WHITE);
clrscr();
printf("\n\tThis program shows calendar of \n");
printf("\n\ta given month. Enter month, year...format is mm-yyyy.\n");

Code Explanation:

textcolor() function is used to change the color of drawing text in c programs.

Declaration :- void textcolor(int 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 textcolor(YELLOW); 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.

C++
/* taking input */
while(TRUE)
{
    fflush(stdin);
    printf("\n\n\tEnter mm-yyyy: ");
    scanf("%d-%d", &Month, &Year);
    if(Year < 0)
    {
        printf("\nInvalid year value...");
        continue;
    }
    if(Year < 100)
        Year += 1900;
    if(Year < 1582 || Year > 4902)
    {
        printf("\nInvalid year value...");
        continue;
    }
    if(Month < 1 || Month > 12)
    {
        printf("\nInvalid month value...");
        continue;
    }
    break;
}    /* End of while loop */

Code Explanation:

Here we started with a while(TRUE) 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.

C++
fflush(stdin);
printf("\n\n\tEnter mm-yyyy: ");
scanf("%d-%d", &Month, &Year);

fflush(stdin); - This function is called to clear the input buffer.

The other lines are used to accept user input in two variables, Month and Year.

C++
if(Year < 0)
{
    printf("\nInvalid year value...");
    continue;
}
if(Year < 100)
    Year += 1900;
if(Year < 1582 || Year > 4902)
{
    printf("\nInvalid year value...");
    continue;
}
if(Month < 1 || Month > 12)
{
    printf("\nInvalid month value...");
    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.

C++
#define LEAP_YEAR ((Year%4==0 && Year%100 != 0)||Year%400==0)
#define TRUE 1
#define CH '-'
#define MAX_NO 91

#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.

C++
int MonthDay[] = {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"};

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:

C++
/*================ FUNCTION TO CALCULATE ZELLER'S ALGORITHM =============*/
int getZeller(int Month,int Year)
{
    int Day = 1, ZMonth, ZYear, Zeller;
    if(Month < 3)
        ZMonth = Month+10;
    else
        ZMonth = Month-2;
    if(ZMonth > 10)
        ZYear = Year-1;
    else
        ZYear = Year;
    Zeller = ((int)((13*ZMonth-1)/5)+Day+ZYear%100+
            (int)((ZYear%100)/4)-2*(int)(ZYear/100)+
            (int)(ZYear/400)+77)%7;
    return Zeller;
}

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.

C++
/*==================== FUNCTION TO GET KEY CODE =========================*/
getkey()
{
    union REGS i,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, left-arrow key, right-arrow-key, up-arrow key, down-arrow key, I, P, etc.

C++
void printchar(char c)
{
    int i;
    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.

C++
void PrintFile(int M,int Y, int Z)
{
    int i, j;
    char filename[12];
    char stryear[5];
    FILE *stream;

    strcpy(filename, MonthName1[M-1]);
    itoa(Y, stryear, 10);
    strcat(filename, stryear);
    strcat(filename, ".txt");

    if((stream=fopen(filename,"w"))==NULL)
    {
        printf("\nError-cannot create file.");
        getch();
        exit(1);
    }

    fprintf(stream, "\n\t\t\t%s %d\n\n\t", MonthName[M-1], 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, "-");

    /* setting starting position */
    fprintf(stream, "\n");
    for(i = 1; i <= Z; i++)
        fprintf(stream, "\t -");

    j = Z;

    /* printing dates */
    for(i = 1; i <= MonthDay[M-1]; 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\tCreated by: Debabrata Das [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.

C++
int i, j;
char filename[12];
char stryear[5];
FILE *stream;

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.

C++
strcpy(filename, MonthName1[M-1]);
itoa(Y, stryear, 10);
strcat(filename, stryear);
strcat(filename, ".txt");

strcpy(des, 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.

strcat(str1, 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"

C++
if((stream = fopen(filename,"w"))==NULL)
{
    printf("\nError-cannot create file.");
    getch();
    exit(1);
}

The above code will try to open the file in write-only 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 "Error-cannot 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.

exit(1); - will exit from the program.

C++
fprintf(stream, "\n\t\t\t%s %d\n\n\t", MonthName[M-1], 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, "-");

/* setting starting position */
fprintf(stream, "\n");
for(i = 1; i <= Z; i++)
    fprintf(stream, "\t -");
j = Z;
/* printing dates */
for(i = 1; i <= MonthDay[M-1]; 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\tCreated by: Debabrata Das [debabrata.dd@gmail.com]");

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

C++
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.

C++
do
{
    /* calculating day of 1st date of given month */
    Zeller = getZeller(Month,Year);
    clrscr();
    printf("\n\n\t\t\t");

    /* printing the corresponding month name */
    textbackground(Month);
    cprintf("%s %d\n",MonthName[Month-1],Year);
    textbackground(BLACK);

    /* adjusting February in case of Leap Year */
    MonthDay[1] = LEAP_YEAR ? 29 : 28;

    /* giving output */
    printchar(CH);

    textcolor(12); /* LIGHTRED */
    printf("\t");cprintf("SUN");
    textcolor(LIGHTGREEN);
    cprintf("     MON     TUE     WED     THU     FRI    SAT");
    textcolor(7);

    printchar(CH);

    /* setting starting position */
    for(i = 1; i <= Zeller; i++)
        printf("\t -");
    j = Zeller;
    /* printing dates */
    for(i = 1; i <= MonthDay[Month-1]; 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(*) Use Left,Right,Up & Down Arrow.");
    printf("\n\n\t\t(*) Press I for New Month & Year.");
    printf("\n\n\t\t(*) Press P for Print to File.");
    printf("\n\n\t\t(*) Press ESC for Exit.\n\n\n\t\t");

    textcolor(11);
    textbackground(9);
    cprintf("Created by: Debabrata Das [debabrata.dd@gmail.com]");
    textcolor(WHITE);
    textbackground(BLACK);

    KeyCode = getkey();         /* getting Key Code */
    if(KeyCode == 72)           /* Up Arrow */
        Year++;
    if(KeyCode == 80)           /* Down Arrow */
        Year--;
    if(KeyCode == 77)           /* Right Arrow */
    {
        Month++;
        if(Month > 12)
        {
            Month = 1;
            Year++;
        }
    }
    if(KeyCode == 75)            /* Left Arrow */
    {
        Month--;
        if(Month < 1)
        {
            Month = 12;
            Year--;
        }
    }
    if(KeyCode == 25)             /* Code of P */
        PrintFile(Month,Year,Zeller);
    if(KeyCode == 23)             /* Code of I */
        goto Top;
}while(KeyCode != 1);    /* End of do-while loop */

Code Explanation:

textbackground(); - This function is used to change current background colour in text mode.

C++
/* adjusting February in case of Leap Year */
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

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


Written By
Product Manager
India India
I'm Debabrata Das, also known as DD. I started working as a FoxPro 2.6 developer then there is a list of different technologies/languages C, C++, VB 6.0, Classic ASP, COM, DCOM, ASP.NET, ASP.NET MVC, C#, HTML, CSS, JavaScript, jQuery, SQL Server, Oracle, No-SQL, Node.Js, ReactJS, etc.

I believe in "the best way to learn is to teach". Passionate about finding a more efficient solution of any given problem.

Comments and Discussions

 
BugWhy doesn't compile? Pin
Jaycod3r1-Dec-19 12:18
Jaycod3r1-Dec-19 12:18 
QuestionCalendar Program Pin
Member 1043702624-Jul-19 1:37
Member 1043702624-Jul-19 1:37 
PraiseGRT Pin
Member 113430804-Apr-17 21:16
Member 113430804-Apr-17 21:16 
QuestionQuery Pin
Haifa Perveez20-Oct-16 5:15
Haifa Perveez20-Oct-16 5:15 
AnswerRe: Query Pin
Debabrata_Das14-Nov-16 0:19
professionalDebabrata_Das14-Nov-16 0:19 
PraiseTHANK YOU Pin
Member 1247599921-Apr-16 23:47
Member 1247599921-Apr-16 23:47 
GeneralRe: THANK YOU Pin
Debabrata_Das22-Apr-16 4:35
professionalDebabrata_Das22-Apr-16 4:35 
Questioncalendar Pin
Member 1168119711-May-15 2:33
Member 1168119711-May-15 2:33 
Hello Brother,
Your calender code is not working in code block compiler ...
AnswerRe: calendar Pin
Debabrata_Das14-May-15 6:00
professionalDebabrata_Das14-May-15 6:00 
SuggestionError Pin
Member 1156650530-Mar-15 0:56
Member 1156650530-Mar-15 0:56 
GeneralRe: Error Pin
Debabrata_Das30-Mar-15 3:26
professionalDebabrata_Das30-Mar-15 3:26 
Questionnice article Pin
Member 114219932-Feb-15 15:13
Member 114219932-Feb-15 15:13 
AnswerRe: nice article Pin
Debabrata_Das2-Feb-15 19:36
professionalDebabrata_Das2-Feb-15 19:36 
QuestionNice Article Pin
Manikandan1010-Jun-14 21:44
professionalManikandan1010-Jun-14 21:44 
AnswerRe: Nice Article Pin
Debabrata_Das10-Jun-14 21:46
professionalDebabrata_Das10-Jun-14 21:46 
GeneralMy vote of 5 Pin
cghao10-Jun-14 21:33
cghao10-Jun-14 21:33 
GeneralRe: My vote of 5 Pin
Debabrata_Das10-Jun-14 21:41
professionalDebabrata_Das10-Jun-14 21:41 
GeneralNice Calendar program Pin
andreas proteus10-Jun-14 4:17
andreas proteus10-Jun-14 4:17 
GeneralRe: Nice Calendar program Pin
Debabrata_Das10-Jun-14 4:28
professionalDebabrata_Das10-Jun-14 4:28 
GeneralRe: Nice Calendar program Pin
andreas proteus10-Jun-14 9:09
andreas proteus10-Jun-14 9:09 
GeneralRe: Nice Calendar program Pin
Debabrata_Das11-Jun-14 18:30
professionalDebabrata_Das11-Jun-14 18:30 
GeneralMy vote of 5 Pin
Sharjith10-Jun-14 1:44
professionalSharjith10-Jun-14 1:44 
GeneralRe: My vote of 5 Pin
Debabrata_Das10-Jun-14 2:08
professionalDebabrata_Das10-Jun-14 2:08 
QuestionNice article Pin
suhel_khan8-Jun-14 20:31
professionalsuhel_khan8-Jun-14 20:31 
AnswerRe: Nice article Pin
Debabrata_Das8-Jun-14 20:46
professionalDebabrata_Das8-Jun-14 20:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.