Home » C programs » Advance C programs

C program to design a digital clock



This program will generate a digital clock using c program. The logic behind to implement this program,

  • Initialize hour, minute, seconds with 0.
  • Run an infinite loop.
  • Increase second and check if it is equal to 60 then increase minute and reset second to 0.
  • Increase minute and check if it is equal to 60 then increase hour and reset minute to 0.
  • Increase hour and check if it is equal to 24 then reset hour to 0.

Implementation of Digital Clock in C

/*C program to design a digital clock.*/
 
#include <stdio.h>
#include <time.h> //for sleep() function
 
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 : 01 : 27






Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.