Creating a Perpetual Calendar in C Language

Perpetual Calendar:Creating a Perpetual Calendar in C LanguageSource Code:

#include <stdio.h>
#include <stdlib.h>
int year(int y){  // Determine if it's a leap year
    if ((y % 4 == 0) && (y % 100 != 0) || y % 400 == 0)
        return 366;  // Leap year
    else
        return 365;  // Common year
}

void printfStar()  // Custom function
{
    printf("*****************************\n");
}

int main(){
    int y;
    int i,j,sum = 0;
    int day ,week;
    int month[12] = {31,28,31,30,31,30,31,31,30,31,30,31};  // Days in each month for common year

    // Input the year for which the calendar is needed
    printf("Please enter the year:\n");
    scanf("%d",&y);
    if(year(y) == 366) month[1] = 29;  // Adjust February for leap year

    // Determine the day of the week for January 1st of the given year (Taylor's formula, January 1, 1900 is Monday)
    for(i = 1990; i < y; i++) sum += year(i);
    week = (sum + 1) % 7;
    printf("The calendar for %d is as follows:\n", y);
    for(i = 0; i < 12; i++){
        printf("\t %d month\n", i + 1);
        printf(" Sun Mon Tue Wed Thu Fri Sat\n");
        printfStar();  // Print star border

        // Calculate the day of the week for the first day of the month
        day = 1; // Start from the first day of a specific month
        for(j = 0; j < week; j++) printf(" ");
        while(day <= month[i]) // Days in each month
        {
            printf("%4d", day);  // Align the output
            day++;
            week = (week + 1) % 7;  // Calculate the day of the week

            // If a line reaches 7 numbers, move to the next line, corresponding to a week
            if(week % 7 == 0) printf("\n");  // New line
        }
        printf("\n"); // Space between months
        printfStar(); // Print star border
        printf("\n");
    }
    system("pause");  // Prevent console from closing
    return 0;
}

*Declaration:This article is compiled from the internet, and the copyright belongs to the original author. If there is any incorrect source information or infringement of rights, please contact us for deletion or authorization matters.

Leave a Comment