Objective:
The objective of this project is to create a program that takes an input number of seconds from the user and then counts down to zero, displaying the remaining time at every second. This is a great way to understand basic loops, input/output operations, and time delays in C++.
Program Code:
#include #include #include using namespace std; int main() { int seconds; // Ask the user for the countdown duration cout << "Enter the number of seconds for the countdown: "; cin >> seconds; // Check if the entered number is valid if (seconds <= 0) { cout << "Please enter a positive number for the countdown." << endl; return 1; } // Countdown loop for (int i = seconds; i >= 0; --i) { cout << "Time remaining: " << i << " seconds" << endl; // Sleep for 1 second (simulate real-time countdown) this_thread::sleep_for(chrono::seconds(1)); } // Display message when countdown is finished cout << "Countdown finished!" << endl; return 0; }
Explanation of Program Structure:
Let’s break down the key parts of the program:
- Libraries: The program includes two important libraries:
<iostream>
: For input/output operations like reading user input and printing output to the console.<thread>
and<chrono>
: For introducing a delay in the program’s execution, which simulates the real-time countdown.
- User Input: The program starts by asking the user to enter the number of seconds for the countdown. If the entered value is not a positive number, the program exits early with an error message.
- Countdown Loop: A
for
loop is used to decrease the value of the countdown from the entered number down to zero. Each second, the program displays the remaining time and then pauses for one second usingthis_thread::sleep_for
. - Ending the Countdown: Once the countdown reaches zero, the program displays a message:
Countdown finished!
.
How to Run the Program:
- Step 1: Open a text editor (e.g., Notepad, Visual Studio Code, or any C++ IDE).
- Step 2: Copy and paste the provided C++ code into a new file.
- Step 3: Save the file with a
.cpp
extension (e.g.,countdown_timer.cpp
). - Step 4: Compile the program using a C++ compiler. If you’re using the command line, you can use the following command:
g++ -o countdown_timer countdown_timer.cpp
- Step 5: After compilation, run the program by typing:
./countdown_timer
- Step 6: Follow the on-screen instructions to enter the number of seconds for the countdown.