Creating a calendar in C programming involves manipulating dates, understanding the days of the week, and formatting the output. Here's a simple example of how you can create a basic calendar for a given month and year. In this example, I'll use the stdio.h
library for input and output operations, and stdbool.h
for boolean values.
#include <stdio.h>
#include <stdbool.h>
// Function to check if a year is a leap year
bool isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return true;
} else {
return false;
}
}
// Function to get the day of the week for a given date
int getDayOfWeek(int day, int month, int year) {
if (month < 3) {
month += 12;
year -= 1;
}
int k = year % 100;
int j = year / 100;
int dayOfWeek = (day + 13 * (month + 1) / 5 + k + k / 4 + j / 4 - 2 * j) % 7;
return dayOfWeek;
}
// Function to print the calendar for a given month and year
void printCalendar(int month, int year) {
// Array to store the number of days in each month
int daysInMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// Adjust February for leap years
if (isLeapYear(year)) {
daysInMonth[2] = 29;
}
// Print the header
printf("Sun Mon Tue Wed Thu Fri Sat\n");
// Get the day of the week for the first day of the month
int dayOfWeek = getDayOfWeek(1, month, year);
// Print leading spaces
for (int i = 0; i < dayOfWeek; i++) {
printf(" ");
}
// Print the days of the month
for (int day = 1; day <= daysInMonth[month]; day++) {
printf("%3d ", day);
// Move to the next line if it's the last day of the week
if ((day + dayOfWeek) % 7 == 0 || day == daysInMonth[month]) {
printf("\n");
}
}
}
int main() {
// Get user input for month and year
int month, year;
printf("Enter month (1-12): ");
scanf("%d", &month);
printf("Enter year: ");
scanf("%d", &year);
// Validate input
if (month < 1 || month > 12 || year < 1) {
printf("Invalid input. Please enter a valid month (1-12) and year (> 0).\n");
return 1;
}
// Print the calendar
printf("\nCalendar for %d/%d:\n", month, year);
printCalendar(month, year);
return 0;
}
This program defines three functions:
isLeapYear
: Checks if a given year is a leap year.getDayOfWeek
: Calculates the day of the week for a given date.printCalendar
: Prints the calendar for a given month and year.
The main
function takes user input for the month and year, validates the input, and then prints the calendar using the printCalendar
function.
Compile and run the program, and you'll be prompted to enter the month and year. The program will then display the calendar for the specified month and year.