Home >>c programs >C Program to design a digital clock

C Program to design a digital clock

C Program to design a digital clock

In this example, we will see a C program to design a digital clock.

In this program the clock will start with the time 00:00:00 and then it will work like a digital clock where it will show the time with hour, minutes and second.

  • STEP 1:Initialize hour, minute, seconds with 0.
  • STEP 2:Run an infinite loop.
  • STEP 3:Increase second and check if it is equal to 60 then increase minute and reset second to 0.
  • STEP 4:Increase minute and check if it is equal to 60 then increase hour and reset minute to 0.
  • STEP 5:Increase hour and check if it is equal to 24 then reset hour to 0.
Example

#include <stdio.h>
#include <time.h>//for sleep() function
#include <unistd.h>
#include <stdlib.h>
int main()
{
int hour, minute, second;
hour=minute=second=0;
while(1)
{
//clear output screen
system("clear");
//print time in HH : MM : SS format
printf("%02d : %02d : %02d ",hour,minute,second);
//clear output buffer in gcc
fflush(stdout);
//increase second
second++;
//update hour, minute and second
if(second==60){
minute+=1;
second=0;
}
if(minute==60){
hour+=1;
minute=0;
}
if(hour==24){
hour=0;
minute=0;
second=0;
}
sleep(1);   //wait till 1 second
}
return 0;
}

Output:
00 : 00 : 00

No Sidebar ads