[Practice 16.2] Why does my code only output 0? | Sololearn: Learn to code for FREE!
Novo curso! Todo programador deveria aprender IA generativa!
Experimente uma aula grƔtis
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 Respostas
+ 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