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

7 Réponses

+ 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;
}

+ 3

For this task thats basically as efficient as it can be.

+ 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.

+ 1

Thank you for confirming 👍

+ 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?

+ 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 😊

+ 1

Ooh I really appreciate your example! I just learnt about the "!" Logical operator, it's really cool! Thank you 😊