Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C

Calendar using C Programming language

4.83/5 (24 votes)
8 Jun 2014CPOL7 min read 236.8K   5.4K  
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)