Clock Simulation

From CompSciWiki
Jump to: navigation, search

Back to the Program-A-Day homepage

Problem

Write a program that will display every second in a 24 hour clock time cycle. Make the output in the format:

00:00:01
00:00:02
00:00:03

Warning: As with many other problems done with nested loops, this program should take some time to execute. The clock must show hours, minutes. and seconds. It will not print everything instantly.

 

...By Students

"Nested loops are probably one of the worst tools to use in terms of performance. If you end up taking Analysis of Algorithms and future classes in performance you will understand how much of a time waster nested loops can be. As you will see in the problem I have presented here there are 3 potential loop structures. Hours loops 24 times, minutes 60 times, and seconds 60 times. Your computer will print the time message 24*60*60 = 86,400 times. When your processor can handle billons of operations, is not that much. But for Java, it can take a couple seconds. If you're into that sort of thing, I encourage you to continue in computer science. If your not interested in performance (as I am) there are still many more areas of computer science to explore. Find out more at www.cs.umanitoba.ca."

Solution

This problem involves the creation of three simple loops that use different integers to display every possible position a clock may have. Begin by opening your class and main method.

 public class ClockSimulator {
    public static void main(String args[])
    {
        ... 

Write your 3 loops, one inside the other, that will count hours, minutes, and seconds. Remember that a 24 hour clock starts at 0 and goes to 23. We will have to start each loop at zero and end it before it reaches 24 or 60 by making the test case less than.

 //loop for hours
for(int hours = 0;hours < 24;hours++)
{
    //loop for minutes
    for(int minutes = 0;minutes < 60;minutes++)
    {
        //loop for seconds
        for(int seconds = 0;seconds < 60;seconds++)
        {
            ... 

Make the output formatted properly. If the value of each loop is less than 10 we want to print a 0 in front of it so it looks like a clock. We can do this with simple if statements that look like this for hours, minutes, and seconds consecutively.

 for(int seconds = 0;seconds < 60;seconds++)
{
    //if hours are less then 10, print a 0 in front
    if(hours < 10)
    {
       System.out.print("0");
    }
    System.out.print(hours + ":");
    ... 

This clock simulator is very basic and may not have any real world function. However, the problem illustrates that loops can cause specific flaws in performance that will be taught in more depth in second year computer science courses.

Code

Solution Code

Back to the Program-A-Day homepage