C program to convert seconds into hours, minutes, and seconds:
In this tutorial, we will learn how to convert a seconds value to hours, minutes, and seconds in C
programming language. The user will enter the second value, and the program will divide it into hours, minutes, and seconds. For example, 3600 seconds is equal to 1 hour, 0 minutes, and 0 seconds. Let’s take a look at the program :
C program to convert an integer to hours, minutes, and seconds:
The following C
program shows how to convert an integer
seconds value to hours, minutes, and seconds. The program takes the value as an input from the user:
#include<stdio.h>
int main(){
//1
int inputSecond;
//2
int hours,minutes,seconds;
int remainingSeconds;
//3
int secondsInHour = 60 * 60;
int secondsInMinute = 60;
//4
printf("Enter the seconds value: ");
scanf("%d",&inputSecond);
//5
hours = (inputSecond/secondsInHour);
//6
remainingSeconds = inputSecond - (hours * secondsInHour);
minutes = remainingSeconds/secondsInMinute;
//7
remainingSeconds = remainingSeconds - (minutes*secondsInMinute);
seconds = remainingSeconds;
//8
printf("%d hour, %d minutes and %d seconds",hours,minutes,seconds);
}
Download the program on GitHub
Explanation:
The commented numbers in the above program denote the step numbers below:
-
Initialize one integer variable,
inputSecond
, to assign the user-input seconds. -
Initialize three integer variables
hours
,minutes
, andseconds
to assign the calculated hours, minutes, and seconds values. The integer variableremainingSeconds
is initialized to use as a temporary variable. -
The variable
secondsInHour
is initialized as 3600 or 60 * 60 i.e. total number of seconds in one hour. Similarly, the variablesecondsInMinute
is initialized as 60 or the total seconds in one minute. -
It asks the user to enter the value of seconds. It reads that value with the
scanf()
function and assigns it to the variableinputSecond
. -
It calculates the hour value by dividing the user input seconds by the total seconds of one hour.
-
Calculate the remaining seconds by subtracting the total seconds in the calculated hour from the total user-given seconds. Using these remaining seconds, calculate the minutes by dividing the seconds by 60.
-
Again, calculate the current remaining seconds. These remaining seconds are the required value for seconds.
-
Print out all hours, minutes, and seconds values.
Sample Output:
Enter seconds : 3600
1 hour, 0 minutes and 0 seconds
Enter seconds : 2345
0 hour, 39 minutes and 5 seconds
Enter seconds : 60
0 hour, 1 minutes and 0 seconds