Continuing our so-called 'Zero-to-Hero' series on Computational programming, today we are going to make a 'real' TIME MACHINE.
Alright, this one is easy. Given a positive number which donates total seconds, we have to find total hours, minutes and seconds, and finally print them all in this format:
- As you've guessed, we need an integer variable to hold the seconds input from the user. Let's call it
totalSecondsand scan it from the console right away.
int totalSeconds; scanf(" %d", &totalSeconds);
- Now, with a simple yet powerful algorithm, we can extract all the hours from
totalSeconds. Just divide
totalSecondsby 3600 (cuz 1h = 3600s).
In C language
int / intis a floor division (see here).
Let's save the extract in a variable called
int hours = totalSeconds / 3600; // since 1h = 3600s
- Minutes! Simply apply module
totalSecondsby 3600. This will give you the remainder seconds after hours are extracted. Reassign the result to
totalSecondsand repeat Step #2 only changing divider into 60 (if you know what I mean ^^).
totalSeconds = totalSeconds % 3600; // this will remove all the hours int minutes = totalSeconds / 60; // since 1m = 60s
- Remaining seconds can be found, yes you guessed it!, by applying modulo operator on
totalSecondsby 60 (think about it 🤔).
int seconds = totalSeconds % 60; // after we remove all the minutes, whatever is left are the remaining seconds
Let's print the result in a humanoid form!
printf("%02d:%02d:%02d\n", hours, minutes, seconds); // 02 - give me at least 2 cell to print, and fill 0s in empty cells
RUN the code live here:
If you liked the
code-crime we committed here, do subscribe and join the