Introduction
On average, people who wear digital watches check their watches 4 to 5 times per hour, which means they wake up their digital watches 60 to 80 times per day.
Source: https://gifer.com/en/ARMM
Since we check our digital watches frequently throughout the day, why not learn how to build them?
In this blog, we will learn how to draw a digital clock using C along with the steps and code.
Digital Clock using C
In this section, we will learn how to draw a digital clock using C. Before we start learning how to draw a digital clock using C, be sure that you know the C basics like data types, looping statements, etc.
In this C program, the digital clock will start with the time 00:00:00. Then it will work like a digital clock where it will show the time with hours, minutes, and second.
Steps
The following steps have to be followed to draw a digital clock using C are:
- Import the required header files.
- Initialize the variables hour, minute, and seconds with 0.
- Run an infinite while loop.
- Increase second and check if it equals 60, then increase minute and reset second to 0.
- Increase minute and check if it equals 60, then increase hour and reset minute to 0.
- Increase hour and check if it equals 24, then reset hour to 0.
Digital Clock using C
Our digital clock will look like the above image. Now let's look at the code to draw a digital clock using C and implement it on Online editor.
Code
// A digital clock using C
// Import the header files
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h>
int main() {
int hour = 0;
int minute = 0;
int second = 0;
while(1) {
// Clear the output on screen
// for windows use system("cls")
system("clear");
// Print the time in HH : MM : SS format
printf("%02d : %02d : %02d ",hour,minute,second);
// Clear the output buffer in gcc
fflush(stdout);
// Increment 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;
}
// Wait for 1 second
sleep(1);
}
return 0;
}
Output
You can practice by yourself with the help of online c compiler.