Group
Real-Time Programming in C++
Objective
Write a C++ program that takes a number as input from the user and counts down to 0, updating every second. Use a loop to decrement the number and display the countdown in the console. Ensure that the program waits for one second between each update.
Implement a countdown timer that counts from a specific number to 0.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the input-output stream library
#include <thread> // Include the thread library to implement delays
#include <chrono> // Include the chrono library for time-related functions
using namespace std;
// Function to implement the countdown timer
void countdown(int start) {
while (start >= 0) { // Loop until the start number reaches 0
// Display the current countdown number
cout << "\r" << start << flush;
// Wait for 1 second before the next countdown
this_thread::sleep_for(chrono::seconds(1));
// Decrease the countdown number by 1
start--;
}
cout << "\nCountdown finished!" << endl; // Notify when countdown is complete
}
int main() {
int number;
cout << "Enter a number to start the countdown: ";
cin >> number; // Input a starting number for the countdown
// Call the countdown function with the input number
countdown(number);
return 0;
}
Output
Enter a number to start the countdown: 5
5
4
3
2
1
0
Countdown finished!