Even in deep space, lasers should have a cool sound effect. Learn how to add one to your laser blaster LEDs that are triggered with a button press.
The code in the editor below already works. Just plug in your Code Rocket and press upload to see what it does! Tinker with it and make changes to see what each line of code controls.
New Concept: If - Else If - Else
The sequence of statements ‘if’, followed by ‘else if’, followed by ‘else’ creates a priority in the program around which condition is checked first. This concept is useful when you want only one of the possible conditions from your statements to be true. In this case, you want either laser blaster 7 to be on and play its tone, or you want laser blaster 8 to be on and play its tone, or you want neither to be on and no tone to play. There are three scenarios that could happen each time the void loop of the code runs, but you want the program to only be able to pick one of those scenarios.
When you’re designing a program like the one in this example, you need to consider which condition should have ‘priority’ over the others and put that condition in the ‘if’ statement, leaving the other conditions to the ‘else if’ statements that follow after it.
Quiz
If you're having trouble, try to run an experimental program or look at the example code to help you find the answer.1. True or False: You can have an 'else-if' statement without an 'if' statement.
2. True or False: The 'else' statement runs only if the conditions of the 'if' and 'else-if' statements are not true.