Write a count-down timer program in C++

How to print a count down timer in C++:

In this post, we will learn how to create a count-down timer in C++. Our program will take the minute and seconds from the user as inputs and the program will print the seconds in reverse order or count-down.

The main challenge of writing a count-down timer in C++ is to pause the program for one second. We can write one loop like for loop or while loop that will count down from the user given number to 1 and inside that loop, we need to pause the program for 1 second.

Pausing a program or to make it sleep is different in both unix and windows. For both environments, we need to use two different functions. Other than this part, both programs will have same functionality.

C++ count-down timer in unix machine:

In an unix machine like linux or macOS, we can use usleep function that takes the time in microseconds to sleep the program. If we pass 1000000, it will sleep for one second.

This is defined in unistd.h header file.

Below is the complete program to implement count-down timer in unix:

#include <iostream>
#include <ctime>
#include <unistd.h>
using namespace std;

string getCurrentDateTime()
{
    time_t tt;
    struct tm *st;

    time(&tt);
    st = localtime(&tt);
    return asctime(st);
}

int main()
{
    int seconds;
    cout<< "Enter total seconds for the counter"<<endl;
    cin >> seconds;

    while(seconds-- >= 1){
        cout<<"Counter : "<<seconds<<" : " +getCurrentDateTime()<<endl;
        usleep(1000000);
    }
}

Here,

  • getCurrentDateTime method is used to get the current date time. You can ignore it if you want. I added only to show you that the timer runs in 1 second interval.
  • We are asking the user to enter the seconds for the counter and storing it in seconds variable.
  • Using a while loop, we are printing the count-down values. Inside the loop, with current seconds, it also prints the current date time to show you exact values.

Output:

If you run this program, it will print the below output:

Enter total seconds for the counter
10
Counter : 9 : Sat Nov 28 12:44:48 2020

Counter : 8 : Sat Nov 28 12:44:49 2020

Counter : 7 : Sat Nov 28 12:44:50 2020

Counter : 6 : Sat Nov 28 12:44:51 2020

Counter : 5 : Sat Nov 28 12:44:52 2020

Counter : 4 : Sat Nov 28 12:44:53 2020

Counter : 3 : Sat Nov 28 12:44:54 2020

Counter : 2 : Sat Nov 28 12:44:55 2020

Counter : 1 : Sat Nov 28 12:44:56 2020

Counter : 0 : Sat Nov 28 12:44:57 2020

With the time, you can confirm that it executes at 1 second interval.

C++ counter in windows:

In windows machine, we can’t use unistd.h and usleep. For that, use:

  • <Windows.h>
  • Sleep(1000)

That’s it. Other parts of the program will remain same.

You might also like: