0

C++ Module 2: Countdown Challenge

Hello Everyone! Wanted to check if someone could make my code more efficient? Thanks! QUESTION: 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 https://code.sololearn.com/c99WSLtnV0Au/?ref=app https://code.sololearn.com/c99WSLtnV0Au/?ref=app

9th Mar 2022, 5:46 AM
Vuko
Vuko - avatar
7 ответов
+ 4
This is my solution, there are many other solutions that works the same and are as effective. int main() { int n; cin >> n; for(int x=n;x!=0;x--){ cout << x << endl; if(!(x%5)) cout << "Beep\n"; } return 0; }
10th Mar 2022, 9:27 AM
JonB
JonB - avatar
+ 3
For this task thats basically as efficient as it can be.
9th Mar 2022, 5:53 AM
Raul Ramirez
Raul Ramirez - avatar
+ 2
Yeah, if statement takes a bool which means everything bigger than 0 is true. and the ! reverses the bool so true = false, false = true. So when the x%5 is equal to 0 it means false and ! makes it true so the statement can happen.
11th Mar 2022, 8:57 AM
JonB
JonB - avatar
+ 1
Thank you for confirming 👍
9th Mar 2022, 6:04 AM
Vuko
Vuko - avatar
+ 1
Nice code mate. Is it supposed to print both beep & the multiple of 5? Or should it replace the multiple of 5 with the beep? You couldn you use a ternary to make the if print a line or 2 shorter, us that something you are interested in trying?
9th Mar 2022, 6:18 AM
HungryTradie
HungryTradie - avatar
+ 1
Thanks for your response! Yes, it's supposed to print both. I am yet to learn what a ternary is! I would definitely be interested 😊
9th Mar 2022, 6:23 AM
Vuko
Vuko - avatar
+ 1
Ooh I really appreciate your example! I just learnt about the "!" Logical operator, it's really cool! Thank you 😊
10th Mar 2022, 4:50 PM
Vuko
Vuko - avatar