Calendar Generator in C
It is a classic concept in mathematics. Calendar has a day, month and year. It also deals with leap year which comes 4 year once.
Let us create a calendar generator based on year.
C implementation:
It uses 4 functions to implement this concept.
- LeapYear_check() : Used to check the given year is leap or not.
- getDays_Month() : This gives you number of days in a month.
- Get_firstDay() : It gives the first day of the month using Zeller’s Congruence.
- Display_month() : displays the month of the calendar.
Finally, main() function reads the year from the user.
C Program:
#include <stdio.h>
// Check the leap year
int LeapYear_check(int year1) {
return (year1 % 4
== 0 && year1 % 100 != 0) || (year1 % 400 == 0);
}
// Get the number of days in a month
int getDays_Month(int month1, int year1) {
int days1[] = {31,
28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month1 == 2
&& LeapYear_check(year1)) return 29;
return
days1[month1 - 1];
}
// Find the weekday of the first day of a month using
Zeller’s Congruence
int get_firstday(int day1, int month1, int year1) {
if (month1 < 3)
{
month1 += 12;
year1--;
}
int k = year1 %
100;
int j = year1 /
100;
int weekday1 =
(day1 + 13*(month1 + 1)/5 + k + k/4 + j/4 + 5*j) % 7;
return (weekday1 +
6) % 7; // sometimes make Sunday = 0
}
// Display the calendar for a month
void display_Month(int month1, int year1) {
char *months1[] =
{
"January", "February", "March",
"April", "May", "June","July",
"August", "September", "October", "November",
"December" };
printf("\n
------------%s-------------\n", months1[month1 - 1]);
printf(" Sun Mon Tue Wed Thu Fri Sat\n");
int days1 =
getDays_Month(month1, year1);
int start_Day =
get_firstday(1, month1, year1);
for (int i = 0; i
< start_Day; i++) {
printf(" ");
}
for (int day1 = 1;
day1 <= days1; day1++) {
printf("%4d", day1);
if ((day1 +
start_Day) % 7 == 0) printf("\n");
}
printf("\n");
}
// Main function
int main() {
int year1;
printf("Enter
year: ");
scanf("%d", &year1);
for (int month1 =
1; month1 <= 12; month1++) {
display_Month(month1, year1);
}
return 0;
}
Output:
This output is sample one for 2 months. But this program
gives you entire year.
Hope, you understood the concept and the program
implementation. Keep Coding!!!!
Comments
Post a Comment