Time Machine - Computational Thinking 101 | Beginner

wahidustoz

Wahid Abduhakimov

Posted on January 22, 2021

Time Machine - Computational Thinking 101 | Beginner

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

  1. 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);
Enter fullscreen mode Exit fullscreen mode
  1. Now, with a simple yet powerful algorithm, we can extract all the hours from totalSeconds. Just divide totalSeconds 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
Enter fullscreen mode Exit fullscreen mode
  1. Minutes! Simply apply module (%) to totalSeconds by 3600. This will give you the remainder seconds after hours are extracted. Reassign the result to totalSeconds 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
Enter fullscreen mode Exit fullscreen mode
  1. 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Tadaaa, a time machine!

Alt Text


RUN the code live here:


If you liked the code-crime we committed here, do subscribe and join the subssquad!

💖 💪 🙅 🚩
wahidustoz
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.

Related