Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Write a C program for time conversions using if and elseif statements
In this tutorial, we will learn how to convert time from 24-hour format (also known as military time) to 12-hour format using C programming with if and else if statements. The 24-hour format uses hours from 00 to 23, while the 12-hour format uses hours from 1 to 12 with AM/PM indicators.
Syntax
if (condition1) {
// statements
} else if (condition2) {
// statements
} else {
// statements
}
Algorithm
Start:
Step 1: Enter time in 24 hr format (hour:minute)
Step 2: Check the conditions using if-else if statements:
i. If (hour == 0)
Display as 12:mm AM (midnight hour)
ii. Else if (hour < 12)
Display as hour:mm AM (morning hours)
iii. Else if (hour == 12)
Display as 12:mm PM (noon hour)
iv. Else
Display as (hour % 12):mm PM (afternoon/evening)
Stop
Example Program
The following program reads time in 24-hour format and converts it to 12-hour format using conditional statements −
#include <stdio.h>
int main() {
int hr, min;
printf("Enter the time in 24 hour format (HH:MM): ");
scanf("%d:%d", &hr, &min);
printf("The 12 hour format time: ");
if (hr == 0) {
printf("12:%.2d AM<br>", min);
}
else if (hr < 12) {
printf("%d:%.2d AM<br>", hr, min);
}
else if (hr == 12) {
printf("%d:%.2d PM<br>", hr, min);
}
else {
printf("%d:%.2d PM<br>", hr % 12, min);
}
return 0;
}
Output
Enter the time in 24 hour format (HH:MM): 22:37 The 12 hour format time: 10:37 PM
How It Works
- Hour 0 (00:xx): Represents midnight, displayed as 12:xx AM
- Hours 1-11 (01:xx to 11:xx): Morning hours, displayed as-is with AM
- Hour 12 (12:xx): Noon hour, displayed as 12:xx PM
- Hours 13-23 (13:xx to 23:xx): Afternoon/evening hours, subtract 12 and display with PM
Key Points
- The
%.2dformat specifier ensures minutes are displayed with leading zeros when less than 10 - The modulo operator
%is used to convert hours greater than 12 to 12-hour format - Special handling is required for hour 0 (midnight) and hour 12 (noon)
Conclusion
Time conversion from 24-hour to 12-hour format using if-else if statements is straightforward. The key is handling special cases like midnight (00:xx) and noon (12:xx) correctly while applying the modulo operation for afternoon hours.
Advertisements
