Loops: Doing Things More Than Once
Sometimes you need to do something many times — go through a list, count up to a number, keep asking until the user gives a valid answer. That's what loops are for.
The most common loop is iterate. Let's start with a range:
start:
iterate i in 1 to 5
print("Step {i}")Step 1
Step 2
Step 3
Step 4
Step 5Clean counts from the first number to the last, running your code each time with i set to the current value.
When you have a list, iterate goes through every item for you:
start:
list<string> fruits = ["apple", "banana", "mango"]
iterate fruit in fruits
print("I like {fruit}")I like apple
I like banana
I like mangoUse while when you need to keep going until a condition changes:
start:
integer count = 1
while count <= 3
print("Count is {count}")
count = count + 1Count is 1
Count is 2
Count is 3Use break to exit a loop early. Use continue to skip the rest of the current step and move to the next.
Quick recap
- iterate i in 1 to 10 — counts from 1 to 10
- iterate item in myList — goes through every item in a list
- while condition — keeps going as long as the condition is true
- break — exits the loop immediately
- continue — skips to the next iteration
- Don't forget to update your counter in a while loop — or it runs forever!