🕐📚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>34#ifdef _WIN325 #include <windows.h>6 #define SLEEP(x) Sleep(x * 1000)7#else8 #include <unistd.h>9 #define SLEEP(x) sleep(x)10#endif1112int 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 overwrite24 printf("\r %02d:%02d:%02d ",25 local->tm_hour,26 local->tm_min,27 local->tm_sec);28 29 fflush(stdout); // Force output30 SLEEP(1); // Wait 1 second31 }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.
Related Examples
Want to Learn More?
Explore our comprehensive tutorials for in-depth explanations of C programming concepts.
Browse Tutorials