Problem
How to convert the time from 24 hr format to 12 hr format using C Programming language?
Solution
Read the time value from the user (at run time). It has to be converted into 12 hr format from 24 hr.
Algorithm
Start: Step 1: Enter time in 24 hr format Step 2: check the condition i. If(hour==0) Print min Ii. Elseif(hour<12) Print hour,min iii. Elseif(hour==12 Print hour,min iv. Else Print hour % 12,min Stop:
Program
#include<stdio.h>
int main(){
int hr,min;
printf("enter the time in 24 hour format:");
scanf("%d:%d",&hr,&min);
printf("The 12 hr format time:");
if(hr==0){
printf("12:%.2d AM\n",min);
}
else if(hr<12){
printf("%d:%.2d AM\n",hr,min);
}
else if(hr==12){
printf("%d:%.2d PM\n",hr,min);
}
else
printf("%d:%.2d PM\n",hr % 12,min);
return 0;
}Output
enter the time in 24 hour format:22:37 The 12 hr format time:10:37 PM