5.0 Control Flow and Logic
5.0 Control Flow and Logic
Effective programming requires the ability to control the flow of execution. Rather than running commands in a simple, linear sequence, control flow structures allow programs to repeat actions and make decisions. Logo provides robust structures for iteration (repetition) and conditional logic, enabling developers to create programs that can execute non-linearly based on defined conditions or data states. These constructs are fundamental for building algorithms that are efficient, responsive, and intelligent. From here, the next step is to organize these logical blocks into reusable procedures.
5.1 Iteration
Iteration is the process of repeating a task a specified number of times. Logo accomplishes this with the repeat command.
- Syntax: repeat [number] [commands]
- Usage: The keyword repeat is followed by the number of repetitions. The sequence of commands to be repeated must be enclosed in square brackets [].
- Example: repeat 4 [fd 100 rt 90] draws a square.
- Nesting: repeat loops can be nested inside one another to create more complex patterns.
5.2 Conditional Logic
Conditional logic allows a program to execute different commands based on whether a certain condition is true.
- while Loop: The while loop executes a block of commands as long as a specified condition remains true.
- Syntax: while [condition] [commands]
- Example: while [:n < 100] [ make “n :n + 5 fd :n rt 90 ]
- if Statement: The if statement executes a block of code a single time, but only if its associated condition is true.
- Example: if :r = 0 [fd 20]
5.3 Randomization
Logo can introduce unpredictability into programs using the random command, which is useful for creating variety or simulating random events.
- Function: The command random [number] generates a random integer between 0 and one less than the specified [number]. For example, random 3 will produce 0, 1, or 2.
- Application in Logic: The random command is often used with conditional statements to make decisions. In the source example, random 3 is used to unpredictably select one of three possible turtle movements, with each outcome tied to a separate if statement.