Introduction to Robotics/Control Flow/Lecture/Teachers

Control Flow
A computer can only perform one instruction at a time. In a program, we write the instructions that we want the computer to perform, starting at the top of the page. The processor reads each instruction at a time and performs that action before moving down to the next instruction. The order in which instructions are performed is known as the control flow of a program. The regular control flow of a program is from the top of the code to the bottom. However, there are several tools we can use to change the control flow, so that the robot can do more complicated things. An example of this is the FOR / NEXT loops that we saw in the first lab. A FOR / NEXT loop allows us to move the control flow back to the top of a block of code, so that we can repeat it multiple times. There are other control flow tools that we can use, such as nested loops, branches, and subroutines.

FOR / NEXT Loops
We have already seen the FOR / NEXT loop in the previous lab, but what does it do? A FOR / NEXT loop uses a counter variable to count the number of loops. Each time we perform the loop, we increase the value of the counter variable. The NEXT keyword moves the control flow back to the top of the loop. If your loop does not have a NEXT keyword, it will not repeat. Once the counter variable reaches the TO value, the loop exits, and the control flow continues after the loop.

We can “nest” FOR / NEXT loops. “nesting” means that we put one loop inside another loop. When we nest FOR / NEXT loops, we need to use different counter-variables for each loop.

If we use the same counter-variable, the variable will be changing in the inner loop, and the outer loop will not work correctly:

How it Works
A FOR / NEXT loop does several things:


 * 1) Set the counter variable to the starting value.
 * 2) perform the instructions inside the loop.
 * 3) Increment the counter variable by 1.
 * 4) Check the counter variable. If it is equal to the TO value, the loop ends.
 * 5) If the counter variable is not equal to the TO value, go to #2

Labels and GOTO
Labels are like destination points. When we put a label in our code, we can jump to it using a GOTO statement.

Branches
Computers can compare numbers together, to determine if they are equal, greater then, or less then. Using an IF / THEN, we can jump to different locations if the comparison is true. If the comparison is not true, then the IF / THEN does nothing, and the control flow moves to the next instruction.

Subroutines
Subroutines allow us to reuse code so that we can avoid having to copy + paste things that need to be repeated.