+ 2

Putting an if statement in a while loop

I'm doing my count down project and when I introduce an if statement it will interrupt the loop or only output what fits the if statement

20th Aug 2021, 5:28 PM
Gunner
8 Respostas
+ 2
David Garcia Prados, What makes the use of `break` a bad practice? isn't it a valid statement in a loop?
20th Aug 2021, 8:10 PM
Ipang
+ 1
Isn't this what actually should happen? Can you please link your code and explain which output you expect?
20th Aug 2021, 5:37 PM
Lisa
Lisa - avatar
+ 1
There are two options: 1. You can use a break statement but it's a bad practice. 2. Add the negation of condition in while.
20th Aug 2021, 5:38 PM
David García Prados
+ 1
#include <iostream> using namespace std; int main() { int n; cin >> n; //your code goes here while(n > 0){ cout << n << endl; if(n % 5 == 0){ cout << "Beep" << endl; } n--; } return 0; }
20th Aug 2021, 7:07 PM
David García Prados
0
Yes thank you that is very helpful
20th Aug 2021, 6:33 PM
Gunner
- 1
#include <iostream> using namespace std; int main() { int n; cin >> n; while (n > 0){ cout << n << endl; n--; if (n %= 5){ cout << "beep" << endl; } } return 0; }
20th Aug 2021, 6:25 PM
Gunner
- 1
When it runs it's supposed to out put a countdown to 1 from the input with the word beep following any number divisible by 5
20th Aug 2021, 6:26 PM
Gunner
- 1
Like this? I changed the n%=5 part https://code.sololearn.com/ckorY28qKwk8/?ref=app
20th Aug 2021, 6:32 PM
Lisa
Lisa - avatar