digital clock in C

C series for 1st sem students: Lets code a digital clock in C

Posted on Posted in Blogs, Technology

Today we are going to do a fun project. We will code a digital clock in C. Learning a programming language is useless if you can’t make cool applications with it. Building such things are way easier in modern languages like C#, java or javascript. But with a good understanding of the basic programming concepts, and using some library functions provided in various header files, we can make some really cool apps. I have discussed about header files in a previous blog. If you’ve missed that blog, check here.

First of all let us plan out the process to make the clock. The required steps are:

  1. Get the current time, and print it in hour:minute:seconds format.
  2. Wait for 1 second.
  3. Clear the output.
  4. Get the current time again and display it. Repeat the process.

The above may be viewed as the algorithm of our program. By the simplest of definitions, an algorithm is a process or set of rules to be followed in calculations or other problem-solving operations, especially by a computer.

Now let us look at the requirements for each step. For the first step we need a function that can return us the system time. For this we will use the time() function defined in the header file time.h. This file also contains a function strftime() which we’ll use to format the time in H:M:S format.

For the second step, we will use the function sleep() defined in the header file unistd.h. The function takes an integer as argument in seconds.

For the third step, we will simply print some blank spaces on top of the previous output. We will also use the escape character ” \r ” which represents a carriage return. Unlike a newline ” \n “, this will print the output from the beginning of the same line. So the blank spaces will overwrite the previously displayed time.

In the last step, we will employ a process called a loop. We haven’t yet discussed about loops in this series, but showing you a cool application of loops first may trigger an interest in you to learn and apply loops in other cool apps. A loop causes some code to run again and again until/(as long as) some condition is satisfied. We will use a condition which will always be satisfied, so the loop will run forever.

digital clock in C

For the first step, we write most of the code in our program. This will be a lot to grasp just yet, but as we go forward and learn concepts like structures and pointers, things will get clearer. Till then download this code { here }, and run it in your PCs and marvel at the power of programming.


If you liked this article please comment and show your support and interest so that I’ll be motivated to continue this effort. Like our facebook page if you haven’t already. And if you have any questions please comment. I’ll try to reply all.