+ 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
8 Respostas
+ 2
David Garcia Prados,
What makes the use of `break` a bad practice? isn't it a valid statement in a loop?
+ 1
Isn't this what actually should happen?
Can you please link your code and explain which output you expect?
+ 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.
+ 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;
}
0
Yes thank you that is very helpful
- 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;
}
- 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
- 1
Like this?
I changed the n%=5 part
https://code.sololearn.com/ckorY28qKwk8/?ref=app