In this tutorial, you'll learn how to write a C program that displays a greeting message ("Good Morning", "Good Afternoon", or "Good Evening") based on the current time. This simple program is useful for practicing working with time functions in C and conditional logic.
What is a Time-based Greeting?
A time-based greeting changes depending on the current time. The program will determine the current hour and display one of the following messages:
- Good Morning if the time is between 5 AM and 11:59 AM.
- Good Afternoon if the time is between 12 PM and 4:59 PM.
- Good Evening if the time is from 5 PM to 4:59 AM.
This type of program can be used in interactive applications to provide a more personalized user experience.
Greeting Program Based on Time in C
Here is a C program that uses the time.h
library to fetch the current system time and display an appropriate greeting based on the hour:
Example:
#include <stdio.h>
#include <time.h> // Necessary for working with time functions
int main() {
time_t currentTime;
struct tm *localTime;
int hour;
// Get the current system time
time(¤tTime);
// Convert it to local time format
localTime = localtime(¤tTime);
// Extract the hour from the local time structure
hour = localTime->tm_hour;
// Display appropriate greeting based on the current hour
if (hour >= 5 && hour < 12) {
printf("Good Morning!\n");
} else if (hour >= 12 && hour < 17) {
printf("Good Afternoon!\n");
} else {
printf("Good Evening!\n");
}
return 0;
}
Program Output:
For example, if the current time is 10 AM, the output will be:
Good Morning!
If the current time is 3 PM, the output will be:
Good Afternoon!
If the current time is 7 PM, the output will be:
Good Evening!
Scenario Example:
Consider a scenario where the current time is 14:30 (2:30 PM). The program will extract the hour as 14
and match it with the condition (hour >= 12 && hour < 17
), resulting in the message "Good Afternoon!" being displayed.
Conclusion
This tutorial has demonstrated how to create a simple C program that displays a greeting message based on the current time. The program uses the time.h
library to get the current system time and checks the hour to determine the appropriate greeting. This is a great way to practice working with time functions and conditionals in C.