Recap of Switch Statements

What We’ve Covered So Far

Here’s what a switch statement looks like:

With the variable ‘parameter’ put in the top parentheses, the switch statement goes through each case. If the parameter is equal to the value of the case, then it runs all statements in that case statement until it reaches a break. If the parameter doesn’t equal any value, it will run the code in the default statement.

The break; command at the end of each case statement causes the switch statement to stop running code inside the switch statement.

The default statement at the end of the case statements runs if the parameter doesn’t match any of the other case statements.

Questions and Activities to Try

1. Create a switch statement that will print different words or sentences on the LCD screen depending on the value of a variable. Change the variable and reload the code a couple times to see if it works. Click here for help with printing words and sentences out on the LCD screen.

2. Now try using Sparki’s Ultrasonic Distance Sensor and storing the value you get from a reading in a variable. Then use that variable to control your switch statement. You may need to change the case statements that you have so that they use the full range reached by the Ultrasonic sensor.  

Next Step:

Now that you understand switch statements we’ll move on to the incredibly important for loop.

Next Lesson – For Loop