C Program to convert Seconds into Hours, Minutes and Seconds

In our daily life we all encounter problems physically as well as mentally.
Let us take an example: you are downloading an HD quality movie from the internet and the download manager shows the time remaining for download as ‘3570 seconds’.
If you are not really good in maths, then definitely you will get irritated and will shut down your PC or let it download for an undetermined amount of time.

But, if we convert 3570 seconds into hours, minutes and seconds format it will be something like 59 minutes 30 seconds. To solve such problems, software and applications have codes which do the task of converting them and display the output to the user in a much simpler format.
In this article, we will make a program which will convert user entered seconds into hours, minutes and seconds.

Logic

We have two cases here:
1) When the number of minutes is greater than 60.
2) When the number of minutes is lesser than 60.

When the number of minutes will be greater than 60, then we will have to include the hours; else, it is unnecessary.
The formulae that we will be using to split the seconds into equivalent minutes and seconds for case 1 is…
If user enters 2300, then
2300/60 = 38 … (minutes)
2300\%60 = 20 … (seconds)
Here, 38 is the number of minutes and 20 is the number of seconds.
Thus, 2300 secs = 38 mins and 20 secs.

For case 2, lets take an example where a user enters integer seconds more than 3600 (3600 seconds = 1 hour).
If user enters 4567, using the above formulae,
4657/60 = 77 … (minutes)
4567\%60 = 37 … (seconds)
The formulae that we will be using to split the minutes into equivalent hours and minutes for case 2 is…
77/60 = 1 … (hours)
77\%60 = 17 … (minutes)
Thus, 4567 secs = 1 hour 17 mins 37 secs.
Now, we have the logic in our mind.
Time for Coding!

C program for above logic:

#include<stdio.h> int main(){ int n,hr,min,sec; printf("Enter seconds:"); scanf("\%d",&n); if(n>3600){ min = n/60; sec = n\%60; hr = min/60; min = min\%60; printf("Converted format \%d hour \%d mins \%d secs",hr,min,sec); } else{ min = n/60; sec = n\%60; printf("Converted format \%d mins \%d secs",min,sec); } }

Output:

Thanks for reading

Tweet your queries and feedback to @PsychoCodes or leave a message on our Facebook page. You can also comment your questions below.

Also, don’t forget to subscribe to our Newsletter.

If you like this article, then please share it and help us grow.


Preorder and Postorder Traversal of binary tree in Python
02 September 2018

Binary Tree in Python
02 September 2018

Image Sharpening by High Pass Filter using Python and OpenCV
17 August 2018

Explaining Register variables in C with examples
17 August 2018

C program to generate all combinations of N-Bit Binary String
10 July 2018

Data Autosave System using PHP, MySQL and AJAX
06 July 2018

Понравилась статья? Поделиться с друзьями:
Добавить комментарий