🕒

C Programming Digital Clock Project

May 16, 2025

Digital Clock Project in C

Overview

  • Create a digital clock using C programming.
  • User can view the current time and it updates every second.

Imports Needed

  • #include <stdlib.h>
  • #include <time.h>
  • #include <stdbool.h>
  • #include <unistd.h> (for Linux/Mac) or #include <windows.h> (for Windows)

Variable Declarations

  • time_t raw_time;
  • struct tm *p_time;
  • bool is_running = true;*

Seed Random Number

  • Set seed using srand(time(NULL));

Welcome Message

  • Print title: "Digital Clock"

Main Loop

  • Use a while loop to continue while is_running is true.
  • Use sleep(1); to update every second.

Update Time

  • Update raw_time using time(&raw_time);
  • Call p_time = localtime(&raw_time); to convert to local time.

Print Time

  • Print current time using printf() with formatting:
    • Hour: %02d, Minute: %02d, Second: %02d
  • Use p_time->tm_hour, p_time->tm_min, p_time->tm_sec

Exit Condition

  • Set is_running = false; to exit the loop if needed.

Complete Code Snippet

#include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdbool.h> int main() { time_t raw_time; struct tm *p_time; bool is_running = true; printf("Digital Clock\n"); while (is_running) { time(&raw_time); p_time = localtime(&raw_time); printf("%02d:%02d:%02d\r", p_time->tm_hour, p_time->tm_min, p_time->tm_sec); fflush(stdout); sleep(1); } return 0; }

Summary

  • The program runs in a loop, updating the displayed time every second while tracking the hours, minutes, and seconds.