0

Counting down using C++

I completed a practice while loop lesson for C++ where they ask for user input pertaining to total number of seconds. We are to then create a while loop that counts down from the number given on down to "0". Initially I wrote: Int seconds; cin>>seconds; while(seconds >= 0){ seconds--; cout<<seconds<<endl; { No matter the input starting number, my output would start at 1 number less than the input number anf countdown to -1. To beat this I just created a variable: int num = secounds + 1 and then wrote in the while loop: while(num > 0){ num--; cout<<num<<endl; Whith this, I received all green lights and passed. I feel like this was a cheat and want to know if this is the way a countdown is to be done in C++ or if there is a better (correct) way and if so, why did I get the result of counting down from a number 1 less than the given number on down to -1, with my original entry?

17th Dec 2021, 12:22 AM
Robert Haugland
Robert Haugland - avatar
2 Answers
+ 4
You count down before printing. Just reverse the order of the statements inside the loop to print first and count down after.
17th Dec 2021, 12:32 AM
Simon Sauter
Simon Sauter - avatar
+ 1
Simon, Thanks. Your advice worked. So simple!
17th Dec 2021, 4:31 AM
Robert Haugland
Robert Haugland - avatar