Star Student Builder logoStar Student Builder
← Young Developers Lesson 4Std 9-12

States and Conditions

A condition is not only a filter. Keep a number that records what state your program is in, test it each round, and the same loop behaves differently at different moments. Traffic lights, games and lifts are all built on this one idea.

πŸ’‘ The idea

A variable can hold the state a program is in, and conditions decide how it behaves in each state.

  • State means the information a program is holding about itself right now.
  • A variable holds the state. An if reads it and decides what to do.
  • Cover every case: less than, greater than, and exactly equal.
  • When no branch matches, nothing changes and the old setting stays in force.
  • A counter is the simplest state of all: it knows how far through the loop you are.

πŸ“˜ Words to know

state
what a program is holding in memory right now
condition
a test that is either true or false
counter
a variable that counts the rounds of a loop

πŸ‘€ Watch this

A square spiral that is blue while the step is small, green at exactly 80, and red from then on.

set d 20
repeat 10 [
if d < 80 [ colour blue ]
if d = 80 [ colour green ]
if d > 80 [ colour red ]
forward d
right 90
change d by 15
]
What this program draws
What it draws

✍️ Your turn

  1. Run it and find the single green side.
  2. Remove the middle if and explain why the 80 side is now blue.
  3. Change the threshold from 80 to 50 in all three tests.
  4. Add a fourth rule that sets width 10 once d passes 120.
  5. Describe in one sentence what the variable d represents.

🎯 Challenge: Keep a counter as your state, and use it to draw the first half of an octagon with a thin pen and the second half with a thick one.

Show me one answer
set n 1
repeat 8 [
if n < 5 [ width 2 ]
if n > 4 [ width 10 ]
forward 60
right 45
change n by 1
]

Your program
Ask GuruAcharya Samayeshwar