0

Why do this code output “Beep” in the bottom? It has to stop after number “5”, no?

https://code.sololearn.com/c957ghJ9H5zD/?ref=app

27th Nov 2022, 9:30 AM
Ksenia Lis
8 Answers
+ 1
Zero % any number yields zero. The `if` conditional verifies that <n> % 5 == 0 and prints "Beep" Notice you subtract <n> before the `if` conditional block. When <n> was 1, code prints <n>, subtract it by one, and then <n> (being zero) gets passed to `if` conditional for verification.
28th Nov 2022, 12:04 PM
Ipang
+ 1
Move the line `n = n - 1` under the `if` conditional block. As it is now, value of <n> is subtracted before the `if` conditional evaluates whether <n> was fully divisible by 5.
27th Nov 2022, 9:58 AM
Ipang
+ 1
thank you for explaining!<3
28th Nov 2022, 12:05 PM
Ksenia Lis
+ 1
#include <iostream> using namespace std; int main() { int n; cin >> n; while (n > 0) { cout << n << endl; n = n - 1; if (n % 5 == 0) { cout << "" << endl; } } return 0; }
29th Nov 2022, 6:50 AM
ARYAN Khuman
ARYAN Khuman - avatar
0
I know that, the question is why its produces "boop" after 1 even though 1 is not divisible by 5?
27th Nov 2022, 10:54 AM
Ksenia Lis
0
No, the "Beep" came from zero, when <n> gets to one, it then decremented to zero, then `if` conditional gets <n> value as zero, not one.
27th Nov 2022, 12:20 PM
Ipang
0
Assuming that you want the program to output "boop" if the no. Is divisible by 5 and output the no if it's not divisible by 5 Try this #include <iostream> using namespace std; int main() { int n; cin >> n; for(int i = n; i > 0; i--){ if(i % 5 != 0){ cout << i << endl; } else { cout << "boop" << endl; } } return 0; }
27th Nov 2022, 12:22 PM
Hirak
Hirak - avatar
0
so 0%5 is completing the conditional? why so?
28th Nov 2022, 10:22 AM
Ksenia Lis