Zeller's Congruence Algorithm in C.

Zeller's Congruence is an algorithm devised by Christian Zeller to calculate the day of the week for any date. The algorithm provides a simple and efficient way to determine the weekday for any date in the Gregorian calendar. 

The formula for Zeller's Congruence is given by:
Zeller's Congruence Algorithm
Where:
  • h is the day of the week (0 = Saturday, 1 = Sunday, 2 = Monday, ..., 6 = Friday)
  • q is the day of the month
  • m is the month (3 = March, 4 = April, ..., 14 = February)
  • K is the year of the century (i.e., year mod 100)
  • J is the zero-based century (actually ⌊ year/100 ⌋)
The result h corresponds to the days of the week, where 0 is Saturday, 1 is Sunday, and so on.

Here's a breakdown of the formula:
  • The term 13(+1)5 adjusts for the months (January and February are counted as months 13 and 14 of the previous year).
  • +4 takes care of the year part.
  • 42 deals with the century adjustment.

Example: Let's calculate the day of the week for March 1, 2023.
Calculation of the day of the week for March 1, 2023
After calculation, we got h value equal to 4 which means March 1, 2023, is Thursday.

C program Implementation of Zeller's Congruence.

// C program to find day of the week for a Date
// Zeller's Congruence
#include <stdio.h>

int zellersCongruence(int day, int month, int year) {
    if (month < 3) {
        month += 12;
        year--;
    }

    int K = year % 100;
    int J = year / 100;

    int h = (day + (13 * (month + 1)) / 5 + K + K / 4 + J / 4 - 2 * J) % 7;

    // Convert h to a more conventional form 
    // (0 = Saturday, 1 = Sunday, ..., 6 = Friday)
    return h % 7;
}

int main() {
    int day = 1, month = 3, year = 2023;

    int dayOfWeek = zellersCongruence(day, month, year);
    char arr[7][10] = {"Saturday", "Sunday", "Monday", 
                       "Tuesday", "Wednesday", "Thursday", "Friday"};
    
    printf("March 1, 2023 is a %s", arr[dayOfWeek]);
    
    return 0;
}
Output:
March 1, 2023 is a Wednesday

In this C program, the zellersCongruence function calculates the day of the week using Zeller's Congruence, and the result is then displayed in a user-friendly format. 

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS