Problem Description: Problem Sample Input and Output
Problem Description: Problem Sample Input and Output
Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. User has to take input
as a string containing a time in 12-hour clock format (i.e.: hh:mm:ssAM or hh:mm:ssPM), where 01
≤ hh ≤12 and 00 ≤ mm,ss ≤59.
Input:- 09:15:55PM
Output:- 21:15:55
Input:- 12:00:00AM
Output:- 00:00:00
Input:- 03:55:50AM
Output:- 03:55:50
Problem Solution:
1- Take input as taken above in sample inputs. (“ %d:%d:%d%s ”, &hh,&mm,&ss,a) or you can
provide inputs to ‘hh’, ‘mm’, ‘ss’ and ‘a’ separately.
2- Check and compare if the string ‘a’ at the end of input is ‘AM’ or ‘PM’.
3- Check the value of hh, and solve accordingly.
Problem Source Code:
#include<stdio.h>
#include<string.h>
int main()
{
int hh,mm,ss;
char a[3];
printf("Enter hours 'hh'");
scanf("%d",&hh);
printf("Enter minutes 'mm'");
scanf("%d",&mm);
printf("Enter seconds 'ss'");
scanf("%d",&ss);
printf("Enter string ‘am’ or ‘pm’");
scanf("%s",&a);
if((strcmp(a,"PM")==0) || (strcmp(a,"pm")==0)
&&(hh!=0)&&(hh!=12))
{
hh=hh+12;
}
if((strcmp(a,"AM")==0)|| (strcmp(a,"am")==0)&&(hh==12))
{
hh=0;
}
printf("The obtained 24 hour format of input is\n");
printf("%02d:%02d:%02d",hh,mm,ss);
return 0;
}
Program Explanation:
The user will give input in 12-hour format, which will contain 4 variables, hh for hours, mm for
minutes, ss for seconds and a string ‘a’ for denoting ‘AM’ or ‘PM’.
After taking the input the user will check if it is ‘PM’ and value of ‘hh’ is anything apart from 00
or 12, it’ll be directly added by 12 and mm,ss will remain same. For example, if the user inputs
hh as 05 ‘PM’, in 24-hour format 05 pm =17 which is nothing but 05+12.
But if it is ‘AM’ and value of hh is 12, the value of hh will be made = 0 because after 23rd hour it’ll
start again from 00, and for the remaining cases if it is ‘AM’ the time in 12-hour and 24-hour
format will remain same. For example, if the user inputs time as 11:47:56AM the output will be
11:47:56 same as it was in 12-hour format, but if the user enters 12:55:21AM the output will be
00:55:21 because the range of hh’s value is between 00 and 23 both inclusive and immediately
after 23rd hour we will be getting 00th hour not 24th .
Runtime Cases