Time Machine - Computational Thinking 101 | Beginner
Wahid Abduhakimov
Posted on January 22, 2021
Continuing our so-called 'Zero-to-Hero' series on Computational programming, today we are going to make a 'real' TIME MACHINE.
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: hh:mm:ss
.
Solution
- As you've guessed, we need an integer variable to hold the seconds input from the user. Let's call it
totalSeconds
and 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 dividetotalSeconds
by 3600 (cuz 1h = 3600s).
In C language
int / int
is a floor division (see here).
Let's save the extract in a variable called hours
!
int hours = totalSeconds / 3600; // since 1h = 3600s
- Minutes! Simply apply module
(%)
tototalSeconds
by 3600. This will give you the remainder seconds after hours are extracted. Reassign the result tototalSeconds
and 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
totalSeconds
by 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
Tadaaa, a time machine!
RUN the code live here:
If you liked the code-crime
we committed here, do subscribe and join the subssquad
!
💖 💪 🙅 🚩
Wahid Abduhakimov
Posted on January 22, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.