Back to Challenge Set 1

Code Challenge: Time Split

Difficulty  

divider

Objective

Take a single number of seconds and break it into hours, minutes, and seconds.

Activity 1.6's adventurer problem split a number once. This splits it twice, and the leftover from the first split becomes the input to the second. That chaining is the whole challenge.

Skills to Practice

  • Division and the remainder operator together
  • Using the result of one calculation as the input to the next
  • Operator precedence and when parentheses are required
  • Naming intermediate values instead of writing one long expression

Why You Cannot Just Divide

There are 3600 seconds in an hour, so the obvious first move is to divide — and to get a real answer instead of a truncated one, you have to write it the way Activity 1.6 taught, with a .0 to force real division. Here is what that gives you:

The Obvious Attempt
double hours = totalSeconds / 3600.0;
Console.WriteLine(hours);
Output
2.573611111111111

Two point five seven hours is a correct answer to a different question. You need 2 hours and then you need to know what is left over, because that leftover is what becomes minutes.

Activity 1.6 gave you both halves of that: % gives the leftover, and subtracting the leftover before dividing gives the whole number.


Tasks

  • Create a new program named cc-time-split.
  • Copy the starter line below into your program.
  • Print the total seconds with a label.
  • Work out the number of whole hours, and store it in a variable.
  • Work out how many seconds are left over after those hours are removed, and store that in a variable too. You will need it twice.
  • From that leftover, work out the whole minutes and the remaining seconds.
  • Print the result on one line, in the format shown below.
Time Split
int totalSeconds = 9265;
// Your code goes below this line.
Then test it

Run your program again with each of these values:

  • 7200 — should be exactly 2 hours, 0 minutes, 0 seconds
  • 59 — should be 0 hours, 0 minutes, 59 seconds
  • 3661 — work out by hand what this should be, then check

All three must come out right. A program that works on 9265 and fails on 59 is a program that got lucky.

Challenge (optional)
  • Add days. A day is 86,400 seconds, and the same pattern extends one more level.

Sample Output

Sample Output
Total seconds: 9265
2 hours, 34 minutes, 25 seconds

Submit

Submit your program file, plus:

  • The output you got for all three test values
  • What 3661 should have been, worked out by hand, written down before you ran it

Predicting the answer first is not busywork. On the exam you will trace code with no way to run it, and this is that skill at its smallest.

Commence Challenge