Loops¶
Loops allow you to repeat code multiple times.
For Loop¶
For loops iterate over a range of numbers.
Basic For Loop¶
The range is inclusive of start, exclusive of end: 0..5 means 0, 1, 2, 3, 4.
Iterating Over Arrays¶
Counting Examples¶
// Count from 1 to 10
for i in 1..11 {
print i;
}
// Even numbers
for i in 0..11 {
if i % 2 == 0 {
print i;
}
}
// Multiplication table
for i in 1..11 {
let result = i * 5;
print "5 × #{i} = #{result}";
}
While Loop¶
While loops repeat as long as a condition is true.
Basic While Loop¶
User Input Loop¶
let running = true;
while running == true {
let input = input("Enter 'quit' to exit: ");
if input == "quit" {
running = false;
} else {
print "You entered: #{input}";
}
}
Sentinel Value Loop¶
let sum = 0;
let number = 0;
while number != -1 {
let input = input("Enter number (-1 to stop): ");
number = int(input);
if number != -1 {
sum = sum + number;
}
}
print "Total: #{sum}";
Nested Loops¶
Loops inside loops:
// Multiplication table
for i in 1..6 {
for j in 1..6 {
let product = i * j;
print "#{i} × #{j} = #{product}";
}
print ""; // Blank line
}
Pattern Printing¶
Common Patterns¶
Accumulator¶
Find Maximum¶
let numbers = [12, 45, 7, 89, 23];
let max = numbers[0];
for i in 1..len(numbers) {
if numbers[i] > max {
max = numbers[i];
}
}
print "Maximum: #{max}";