Embedded C Program for Digital Clock with Time Display
if conditions; for example, if(seconds == 60) { seconds = 0; minutes++; } to keep time correctly.Examples
How to Think About It
Algorithm
Code
#include <stdio.h> #include <unistd.h> int main() { int hours = 0, minutes = 0, seconds = 0; while(1) { printf("%02d:%02d:%02d\n", hours, minutes, seconds); sleep(1); // wait for 1 second seconds++; if(seconds == 60) { seconds = 0; minutes++; } if(minutes == 60) { minutes = 0; hours++; } if(hours == 24) { hours = 0; } } return 0; }
Dry Run
Let's trace the clock starting at 00:00:58 through the code
Initial time
hours=0, minutes=0, seconds=58
Print time
Prints 00:00:58
Increment seconds
seconds = 59
Next loop print
Prints 00:00:59
Increment seconds and reset
seconds = 60 triggers reset: seconds=0, minutes=1
Print updated time
Prints 00:01:00
| hours | minutes | seconds |
|---|---|---|
| 0 | 0 | 58 |
| 0 | 0 | 59 |
| 0 | 1 | 0 |
Why This Works
Step 1: Time variables
We use hours, minutes, and seconds to store the current time values.
Step 2: Increment seconds
Each loop increases seconds by 1 to simulate time passing.
Step 3: Reset and carry over
When seconds reach 60, reset to 0 and increase minutes. Similarly for minutes and hours.
Step 4: Display time
Print the time in HH:MM:SS format using printf with zero padding for clarity.
Alternative Approaches
#include <stdio.h> volatile int hours=0, minutes=0, seconds=0; void timer_interrupt() { seconds++; if(seconds == 60) { seconds=0; minutes++; } if(minutes == 60) { minutes=0; hours++; } if(hours == 24) { hours=0; } } int main() { while(1) { printf("%02d:%02d:%02d\n", hours, minutes, seconds); // timer_interrupt would be called by hardware timer } return 0; }
#include <stdio.h> void delay() { for(long i=0; i<1000000; i++); // simple delay loop } int main() { int h=0,m=0,s=0; while(1) { printf("%02d:%02d:%02d\n", h, m, s); delay(); s++; if(s==60) { s=0; m++; } if(m==60) { m=0; h++; } if(h==24) { h=0; } } return 0; }
Complexity: O(1) per loop iteration time, O(1) space
Time Complexity
The program runs in an infinite loop with constant time operations each cycle, so each iteration is O(1).
Space Complexity
Only a few integer variables are used, so space complexity is O(1).
Which Approach is Fastest?
Using hardware timer interrupts is more efficient and accurate than delay loops or sleep, but requires more setup.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple loop with sleep | O(1) | O(1) | Basic clocks on OS |
| Timer interrupts | O(1) | O(1) | Precise timing on microcontrollers |
| Delay loops | O(1) | O(1) | Simple hardware without OS |