3.3 Loops & Conditionals

Understanding Control Flow

Control flow is the order in which individual statements, instructions, or function calls are executed or evaluated. In block programming, we use loops and conditionals to control the flow of our programs.

Loops in Scratch

Loops allow us to repeat a sequence of blocks multiple times. Scratch provides several loop blocks in the Control category.

1. Repeat Block

repeat (10)
    move (10) steps
    turn cw (15) degrees
end

This will repeat the blocks inside 10 times.

2. Forever Block

forever
    move (10) steps
    if on edge, bounce
end

This will repeat the blocks inside forever (until the stop sign is clicked).

3. Repeat Until Block

repeat until <touching (mouse-pointer v) ?>
    move (5) steps
    play sound (pop v) until done
end

This will repeat until the specified condition is true.

Conditional Statements

Conditionals allow your program to make decisions based on whether a condition is true or false.

1. If-Then Block

if <touching (mouse-pointer v) ?> then
    say [You found me!] for (2) seconds
    change [score v] by (1)
end

2. If-Then-Else Block

if <(score) > (high score)> then
    set [high score v] to (score)
    say [New high score!] for (2) seconds
else
    say [Try again!] for (2) seconds
end

Nesting Loops and Conditionals

You can place loops inside conditionals, conditionals inside loops, and even loops inside other loops.

Example: Countdown with Effects

when green flag clicked
set [count v] to (10)
repeat (10)
    change size by (10)
    change [color v] effect by (25)
    say (join [Countdown: ] (count)) for (1) seconds
    change [count v] by (-1)
    if <(count) = [0]> then
        say [Blast off!] for (2) seconds
        play sound (rocket v) until done
    end
end

Practical Examples

1. Simple Game Loop

when green flag clicked
forever
    if <key (space v) pressed?> then
        change y by (10)
    end
    change y by (-2)
    if <touching (edge v) ?> then
        play sound (boing v)
        point in direction (pick random (-45) to (45))
    end
end

2. Interactive Quiz

when green flag clicked
set [score v] to (0)
ask [What is 5 + 3?] and wait
if <(answer) = [8]> then
    change [score v] by (1)
    say [Correct!] for (1) seconds
else
    say [Incorrect! The answer is 8] for (2) seconds
end

Practice Activity

Create a Scratch program that:

  1. Asks the user for a number between 1-10
  2. Uses a loop to count up to that number
  3. Says each number as it counts
  4. If the number is even, change the sprite's color
  5. If the number is odd, change the sprite's size
  6. When finished, say "All done!" and play a sound