
253 views
C Program to convert 24 Hour time to 12 Hour time
Converting a 24-hour time format to a 12-hour time format in C involves parsing the input time, performing the conversion, and formatting the output correctly. Here’s a C program to do that:
C
#include <stdio.h>
int main() {
int hour, minute;
char am_pm[3];
// Input 24-hour time
printf("Enter 24-hour time (HH:MM): ");
scanf("%d:%d", &hour, &minute);
// Determine AM or PM and adjust hour
if (hour >= 12) {
strcpy(am_pm, "PM");
if (hour > 12) {
hour -= 12;
}
} else {
strcpy(am_pm, "AM");
if (hour == 0) {
hour = 12;
}
}
// Output in 12-hour format
printf("12-hour time: %02d:%02d %s\n", hour, minute, am_pm);
return 0;
}
In this program:
- We declare variables for the hour, minute, and a character array to store “AM” or “PM.”
- The user is prompted to enter a 24-hour time in the format “HH:MM.”
- We determine whether it’s AM or PM based on the value of
hour
. Ifhour
is greater than or equal to 12, it’s PM; otherwise, it’s AM. We also adjust thehour
value if necessary to be within the 12-hour range. - We use
printf
to format and display the 12-hour time, making sure to include leading zeros for single-digit hours and minutes.
Here’s an example of how the program works:
Plaintext
Enter 24-hour time (HH:MM): 15:30
12-hour time: 03:30 PM
This program takes a 24-hour time as input and converts it to a 12-hour time format with “AM” or “PM” designation.