Get Help
Controls
How Robots Decide Which Code to Run
Code is more than functions and variables, though. For code to be useful, it has to be able to make decisions. These pieces of code that make decisions are called control statements. Really the code doesn’t make decisions, it asks questions and takes action depending on the answers to those questions. This is a pretty short lesson. On this page we’ll be covering:Imagine there is a young robot who has enough money to buy just one ice cream, but there are a bunch of different types of ice cream the young robot can buy. The robot has to ask itself some questions to try and figure out which ice cream it should buy. (Don’t ever actually try to feed a robot ice cream- it won’t go over well and you’ll waste some ice cream.)
There are several different ways that the robot can ask itself questions (more than we’ll go over here) and run code depending on that decision. After all- it’s no good if the young robot above makes the decision but then doesn’t take action to buy the ice cream!
Types of Control Code
There are 4 basic types of control statements, we’ll go over all of them: if statements
1 2 3 4 |
if (condition) { statement } |
1 2 3 4 5 6 7 8 9 10 11 12 |
switch ( parameter ) { case value1: statement1; break; case value2: statement2; statement3; break; default: statement4; } |
1 2 3 4 |
while (condition) { statement } |
1 2 3 4 |
for (initialization; condition; increase) { statement } |