Iteration Patterns
Clean Language has several ways to iterate, each suited to a different problem. Ranges for counted loops, list iteration for collections, while for unknown counts. break and continue give you fine control when you need it.
Three iteration forms — range, step, and list:
start:\n string evens = ""\n iterate n in 2 to 10 step 2\n evens = evens + n.toString() + " "\n print("Evens: " + evens)\n\n list<string> days = []\n days.add("Mon")\n days.add("Tue")\n days.add("Wed")\n iterate day in days\n print("Day: " + day)\n\n integer n = 1\n integer total = 0\n while n <= 5\n total = total + n\n n = n + 1\n print("Sum 1-5: " + total.toString())Evens: 2 4 6 8 10 \nDay: Mon\nDay: Tue\nDay: Wed\nSum 1-5: 15iterate n in 2 to 10 step 2 counts by twos. iterate day in days loops over every element by value — no index needed. while n <= 5 runs until the condition is false — use this when the count depends on logic.
break exits early; continue skips to the next iteration:
start:\n list<string> names = []\n names.add("Alice")\n names.add("Bob")\n names.add("Charlie")\n names.add("Diana")\n\n string search = "Charlie"\n integer found_at = -1\n iterate i in 0 to names.length() - 1\n if names[i] == search\n found_at = i\n break\n\n print(search + " at index: " + found_at.toString())\n\n string result = ""\n iterate name in names\n if name.length() < 5\n continue\n result = result + name + " "\n print("Long names: " + result)Charlie at index: 2\nLong names: Alice Charlie Diana break exits the iterate block immediately — the search stops as soon as Charlie is found. continue skips to the next iteration — names shorter than 5 characters are skipped. Both work in iterate-range, iterate-list, and while loops.
Quick recap
- iterate n in start to end — range loop, inclusive on both ends
- iterate n in start to end step N — count by N each iteration
- iterate item in myList — loop over every element by value
- break exits the loop; continue skips to the next iteration