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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | #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:
1 2 3 4 5 6 7 8 9 | 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 |