Loop Examples

Master repetitive tasks with for loops and while loops to automate your programs.

Basic For Loop
Count from 1 to 5 using a for loop
Beginner
for i from 1 to 5
print i
endfor
Counting with While Loop
Use a while loop to count with manual increment
Beginner
count is equal to 1
while count is less than 5 do
print "Count is now: " + count
increment count by 1
endwhile
Multiplication Table
Generate a multiplication table using a for loop
Intermediate
number is equal to 7
print "Multiplication table for " + number

for i from 1 to 10
result is equal to number times i
print number + " x " + i + " = " + result
endfor
Sum Calculator
Calculate the sum of numbers from 1 to 10
Intermediate
sum is equal to 0
print "Calculating sum of numbers from 1 to 10"

for i from 1 to 10
sum is equal to sum plus i
print "Adding " + i + ", sum is now " + sum
endfor

print "Final sum: " + sum
Countdown Timer
Create a countdown from 10 to 1 using a while loop
Intermediate
timer is equal to 10
print "Countdown starting..."

while timer is greater than 0
print timer
decrement timer
endwhile

print "Time's up!"
Number Pattern
Create a number pattern using nested loops
Advanced
print "Number Pattern:"

for row from 1 to 5
for col from 1 to row
print col + " "
endfor
print ""
endfor
Loop Types Comparison
Understanding when to use each type of loop

For Loops

for variable from start to end
# statements
endfor

Best for:

  • • Counting through a known range
  • • Repeating a fixed number of times
  • • Iterating through sequences

While Loops

while condition
# statements
endwhile

Best for:

  • • Condition-based repetition
  • • Unknown number of iterations
  • • More complex stopping criteria
Common Loop Patterns
Frequently used loop structures and their applications

Accumulation Pattern

total is equal to 0
for i from 1 to 10
total is equal to total plus i
endfor

Building up a result over multiple iterations.

Counting Pattern

counter is equal to 0
while counter is less than 10
print counter
increment counter
endwhile

Manually controlling the loop counter.

Search Pattern

found is equal to false
while not found
# check condition
# update found if needed
endwhile

Looking for something until found.

Nested Pattern

for i from 1 to 3
for j from 1 to 3
print i + "," + j
endfor
endfor

Creating tables, grids, or complex patterns.

Important Notes
Warning

Avoid infinite loops

Make sure your while loop condition will eventually become false, or your program will run forever.

Tip

Use descriptive variable names

Instead of "i", use names like "counter", "row", or "item" for clarity.

Tip

Keep loop bodies simple

If your loop body gets too complex, consider breaking it into smaller functions.