0
Please i'm coding a countdown program when it reaches the multiple of 5 it should print out beep but . My code is somehow wrong
#include <iostream> using namespace std; int main() { int n; cin >> n; for (int n =1 ; n<=12;n++){ cout<<n<<endl; if(n%5==0){ cout<<"beep"<<endl; } } return 0;
8 Answers
+ 2
You need to count down not up.
for(; n > 0; n--) {
...
}
You don't need the first part of the for loop, because you're initializing n with cin just before the loop.
Then it needs to be "Beep" not "beep".
+ 1
Thanks
0
after return 0; add closing curly bracket }
0
It's there on my laptop but I don't get expected results
0
You need to make a countdown app.
Given a number N as input, output numbers from N to 1 on separate lines.
Also, when the current countdown number is a multiple of 5, the app should output "Beep".
Sample Input:
12
Sample Output:
12
11
10
Beep
9
8
7
6
5
Beep
4
3
2
1
0
Your code works, but now that I see your comment it doesn't give you the expected result.
Just to make it clear: In the code you wrote variable n that is written in the following statement:
cin >> n
has nothing to do with the variable n in the for loop.
These two variables have the same name (n) but they have different scope.
The problem is that your variable n that's defined INSIDE for loop is SHADOWING your n variable in the main function.
So, to avoid this shadowing (or hiding, it's just a terminology) rename your variable inside for loop.
for (int i = 0; i < n; i++)
cout<<????<<endl;
if(i%5==0)
Now, if the user enters 12, this for loop will iterate 12 times:
i =0
i =1
i =3....
i =5 now if condition is true (5%5==0) and it will beep.
Now you should figure out what should be written instead of ???? so you get your desired output?
cout<<????<<endl;
n
i
or something else?
Tip:
n=12
i = 0,1,2,3,4
how do you get:
12
11
10
...
with these two variables?
0
Ricky Mills Here's the final code:
#include <iostream>
using namespace std;
int main() {
int n;
for (cin>>n;n;n--) {
cout << n << endl;
if (!(n % 5)) cout << "Beep\n";
}
return 0;
}
// Hope this helps
- 1
It doesn't work I don't know why