C program to convert seconds into hour/minute/seconds

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);
}

C program to convert an integer to hours, minutes, and seconds

Download the program on GitHub

Explanation:

The commented numbers in the above program denote the step numbers below:

  1. Initialize one integer variable, inputSecond, to assign the user-input seconds.

  2. Initialize three integer variables hours, minutes, and seconds to assign the calculated hours, minutes, and seconds values. The integer variable remainingSeconds is initialized to use as a temporary variable.

  3. The variable secondsInHour is initialized as 3600 or 60 * 60 i.e. total number of seconds in one hour. Similarly, the variable secondsInMinute is initialized as 60 or the total seconds in one minute.

  4. It asks the user to enter the value of seconds. It reads that value with the scanf() function and assigns it to the variable inputSecond.

  5. It calculates the hour value by dividing the user input seconds by the total seconds of one hour.

  6. 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.

  7. Again, calculate the current remaining seconds. These remaining seconds are the required value for seconds.

  8. 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

You might also like: