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 Respuestas
+ 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