In this article, we are going to learn how to design a digital clock in C language. In this example, we will learn how to design a digital clock, that keeps running on the screen and keep incrementing the time every second.
C Program to design a digital clock
It will start with 00:00:00 and then start incrementing the seconds, once the seconds reach 60, it will increment the minute. Once a minute reaches 60 it will increment the hours.
- Once hours reach to 24 then it will reset the clock back to 00:00:00.
- To perform the logic, we are using a infinite while loop, inside this loop we have the logic to count the seconds, mins and hours.We reset each values once they reach the threshold.
- We are using sleep() function to give a delay of 1 seconds which acts as a clock tick of 1 seconds.
#include <stdio.h>
#include <time.h> //for sleep() function
#include <unistd.h>
#include <stdlib.h>
int main()
{
int Hour, Min, Sec;
Hour = 0;
Min = 0;
Sec = 0;
while(1)
{
system("clear");
printf("Clock: %02d : %02d : %02d ",Hour,Min,Sec);
fflush(stdout);
Sec++;
if(Sec==60)
{
Min+=1;
Sec=0;
}
if(Min==60)
{
Hour+=1;
Min=0;
}
if(Hour==24)
{
Hour=0;
Min=0;
Sec=0;
}
sleep(1);
}
return 0;
}
Output
Clock: 00 : 00 : 05