[Practice 16.2] Why does my code only output 0? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

[Practice 16.2] Why does my code only output 0?

Hello, forgive me if this is a dumb question. I’m still confused on what the ‘while’ statement does. Practice 16.2 wants to make a countdown, it goes something like this: Sample: 5 Output: 5 4 3 2 1 0 This is my code: #include <iostream> using namespace std; int main() { int seconds; cin>>seconds; //your code goes here while (seconds >0) seconds--; cout << seconds; return 0; } In my mind, I’m expecting the computer to take the given integer and minus it by 1 till it reaches 0, with the last deduction being ‘1-1’; whilst outputting each calculated number. However the PC just outputs 0 instead. Any help would be appreciated, just don’t give me the answer directly! Thanks :)

19th Feb 2021, 4:24 AM
Plaush
Plaush - avatar
7 Answers
+ 2
You actually aren't meant to use a do-while loop here as it isn't taught for a few more lessons. A simple while loop is enough to pass. int main() { int seconds; cin >> seconds; while(seconds > -1) { cout << seconds-- << endl; } return 0; }
19th Feb 2021, 8:54 AM
ChaoticDawg
ChaoticDawg - avatar
+ 4
Plaush Because you are printing value outside the while loop. When you don't use curly brackets {} then statement will be of single line statement. It should be like while (seconds > 0) { seconds--; cout << seconds; }
19th Feb 2021, 4:41 AM
A͢J
A͢J - avatar
+ 2
Don't forget the curly braces for your while statement. while () { // Your code here }
19th Feb 2021, 4:32 AM
Zeke Williams
Zeke Williams - avatar
+ 2
Plaush You have to use do while loop here #include <iostream> using namespace std; int main() { int seconds = 0; cin >> seconds; do { cout << seconds << endl; seconds--; } while (seconds >= 0); return 0; }
19th Feb 2021, 4:45 AM
A͢J
A͢J - avatar
+ 1
ChaoticDawg That’s what I did, haha. I just misseed out ‘endl’. Thanks for the answer, though! :)
19th Feb 2021, 8:56 AM
Plaush
Plaush - avatar
0
Zeke Williams It didn’t work. It stopped outputting 0s but it’s now outputting a bunch of random numbers, ranging from 10 to ~200
19th Feb 2021, 4:39 AM
Plaush
Plaush - avatar
0
I Am AJ ! Thank you so much! They didn’t teach me the ‘do’ function, or maybe i just missed it. No pun intended, what does the ‘do’ function do exactly? Does it execute the cout function while the ‘while’ function is running? Edit: I’ve found my orignal error, I missed out ‘endl’. As a result, it didn’t end the line and just printed the results in one line
19th Feb 2021, 4:49 AM
Plaush
Plaush - avatar