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 :)
7 RĂ©ponses
+ 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;
}
+ 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;
}
+ 2
Don't forget the curly braces for your while statement.
while () {
// Your code here
}
+ 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;
}
+ 1
ChaoticDawg Thatâs what I did, haha. I just misseed out âendlâ. Thanks for the answer, though! :)
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
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