Countdown Timer in C++ that Counts from a Specific Number to 0

In this exercise, you will implement a countdown timer in C++ that starts from a specific number and counts down to 0. The program will ask the user to input a number and then display the countdown from that number to 0, updating every second. The program will use a loop to decrement the counter and a delay to simulate real-time countdown. This exercise helps in understanding loops, delays, and basic user input in C++.

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

 Copy 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!

Share this C++ Exercise


More C++ Programming Exercises of Real-Time Programming in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.