Display Days of Week using enum Keyword in C

Print days of week in C

This C program uses enumerated types to display days of week. The enumerated type is then declared as a different name using typedef keyword i.e. enum days to typedef enum days days.

The program has two functions, yesterday() and tomorrow() to calculate the previous and next days based on the current day. These functions handle the circular nature of the days to ensure that correct results is displayed. An array of constant strings, thedays, stores the names of the days of the week.

The function prints for each day of the week, today, yesterday, and tomorrow, both as a string and as a number.

#include <stdio.h>

// Define an enumerated data type for days of the week
enum days { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };
typedef enum days days; // Use "days" as an abbreviation for "enum days"

// Function to calculate yesterday's day based on today's day
days yesterday(days today) {
    return (today + 6) % 7;
}

// Function to calculate tomorrow's day based on today's day
days tomorrow(days today) {
    return (today + 1) % 7;
}

// Array of constant strings representing days of the week
const char * const thedays[] = {
    "Monday", "Tuesday", "Wednesday", "Thursday",
    "Friday", "Saturday", "Sunday"
};

int main(void) {
    days today;

    // Display header
    printf("Today\tYesterday\tTomorrow\n");
    printf("=============================================\n");

    // Iterate through each day of the week
    for (today = MONDAY; today <= SUNDAY; today++) {
        printf("%s = %d \t %s = %d \t %s = %d\n",
            thedays[today], today,
            thedays[yesterday(today)], yesterday(today),
            thedays[tomorrow(today)], tomorrow(today));
    }

    return 0;
}

The output of the above program is:

today     yesterday   tomorrow
============================================
monday = 0   sunday = 6   tuesday = 1
tuesday = 1   monday = 0   wednesday = 2
wednesday = 2   tuesday = 1   thursday = 3
thursday = 3   wednesday = 2   friday = 4
friday = 4   thursday = 3   saturday = 5
saturday = 5   friday = 4   sunday = 6
sunday = 6   saturday = 5   monday = 0
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post