How to Make a Countdown Timer in C++?
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!
Count-Down Timer in C++
To make a countdown timer we can use the <ctime> library, in C++ to fetch the date and time. Combine it with the std::this_thread::sleep_for() function from <thread> along with chrono::seconds(timePeriod) to have the program pause, for a given period of time.
Approach
- 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.
C++ Program to Create a Countdown Timer
The below program demonstrates how we can create a countdown timer in C++.
// C++ program to create a countdown timer
#include <chrono>
#include <ctime>
#include <iostream>
#include <thread>
using namespace std;
// Function to get the current date and time as a string.
string getPresentDateTime()
{
// Declare a time_t variable to hold the current time.
time_t tt;
// Declare a pointer to a tm struct to hold the local
// time.
struct tm* st;
// Get the current time.
time(&tt);
// Convert the current time to local time.
st = localtime(&tt);
// Return the local time as a string.
return asctime(st);
}
int main()
{
// Declare an integer variable to hold the total number
// of seconds for the counter.
int seconds;
// Prompt the user to enter the total number of seconds
// for the counter.
cout << "Enter total number seconds for the counter"
<< endl;
cin >> seconds;
// Loop until the counter reaches zero.
while (seconds >= 1) {
// Print the current value of the counter along with
// the present date and time.
cout << "Time Remaining : " << seconds
<< " : " + getPresentDateTime() << endl;
// Pause the program execution for 1 second.
this_thread::sleep_for(chrono::seconds(1));
// Decrement the counter.
seconds--;
}
cout << "Time's Up!" << endl;
return 0;
}
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)
Contact Us