Control Structures

beginner40 min

Decisions and repetition

Control structures let code branch on a condition or run the same block many times.

If/else chains

Comparison operators

  • == - Equal to
  • != - Not equal to
  • > - Greater than
  • < - Less than
  • >= - Greater than or equal
  • <= - Less than or equal

For loop

Use a for loop when you know how many iterations you need.

While loop

Use while when repetition depends on a condition that may change inside the loop.

Logical operators

  • && - AND (both conditions must be true)
  • || - OR (at least one condition must be true)
  • ! - NOT (reverses the condition)

Examples:

Try It Yourself:

Exercise 1: Control Flow

  • An if/else chain that sets motor speed based on distance to target
  • A for loop that checks multiple sensors
  • A while loop that runs until a button is pressed
  • Combine conditions using logical operators
Write control structures for robot behavior: