🕐📚Intermediate

Print Digital Clock with Current Time

Display running clock

Display a digital clock that updates every second. Uses \\r to overwrite the same line.

Program Code

digital_clock.c
C
1#include <stdio.h>
2#include <time.h>
3
4#ifdef _WIN32
5 #include <windows.h>
6 #define SLEEP(x) Sleep(x * 1000)
7#else
8 #include <unistd.h>
9 #define SLEEP(x) sleep(x)
10#endif
11
12int main() {
13 time_t now;
14 struct tm *local;
15
16 printf("Digital Clock (Press Ctrl+C to stop)\n");
17 printf("=====================================\n");
18
19 while (1) {
20 time(&now);
21 local = localtime(&now);
22
23 // Print time with carriage return to overwrite
24 printf("\r %02d:%02d:%02d ",
25 local->tm_hour,
26 local->tm_min,
27 local->tm_sec);
28
29 fflush(stdout); // Force output
30 SLEEP(1); // Wait 1 second
31 }
32
33 return 0;
34}
Output

Digital Clock (Press Ctrl+C to stop)

=====================================

10:30:45

Note: This program runs indefinitely. Press Ctrl+C to stop it.