![]() |
VOOZH | about |
In C++, countdown timers are valuable components in various applications, aiding in scheduling events, controlling timeouts, or displaying the remaining time. In this article, we will learn how to make a countdown timer in C++.
Example:
Input:
Enter Total Number of Seconds for Countdown Timer: 3
Output:
Time Remaining: 3
Time Remaining: 2
Time Remaining: 1
Time's Up!
To make a countdown timer we can use the <ctime> library, in C++ to fetch the date and time. Combine it with the function from <thread> along with to have the program pause, for a given period of time.
- Take the user input for the total number of seconds for the counter.
- Loop until the counter is 0 and print the counter value along with current date and time.
- Make the program wait for one second before the next iteration of the loop. By using std::this_thread::sleep_for(chrono::seconds(1)).
- Keep decrementing the value of counter by one.
- Repeat steps 2-4 until the counter value is less than or equal to zero.
The below program demonstrates how we can create a countdown timer in C++.
Output
Enter total number seconds for the counter
5
Time Remaining : 5 : Sun May 26 18:24:30 2024
Time Remaining : 4 : Sun May 26 18:24:31 2024
Time Remaining : 3 : Sun May 26 18:24:32 2024
Time Remaining : 2 : Sun May 26 18:24:33 2024
Time Remaining : 1 : Sun May 26 18:24:34 2024
Time's Up!
Time Complexity: O(n), where n is the countdown duration in seconds.
Auxiliary Space: O(1)