🔄 Pętle (for/while/repeat)
Pętle pozwalają powtarzać kod wielokrotnie.
while
let i = 0;
while (i < 5) {
print(i);
i++;
}
do-while
let j = 0;
do {
print(j);
j++;
} while (j < 3);
for (C-style)
for (let i = 0; i < 5; i++) {
print(i);
}
for-in (iteracja)
let items = ["a", "b", "c"];
for (item in items) {
print(item);
}
for (i in 1..5) {
print(i);
}
for (i in 0..<5) {
print(i);
}
for (i in 0..10 step 2) {
print(i);
}
let obj = {x: 1, y: 2};
for (entry in obj) {
print(entry[0] + " = " + entry[1]);
}
repeat
repeat 5 {
print("Hello!");
}
repeat 10 as i {
print("Iteration: " + i);
}
let count = 3;
repeat (count * 2) as n {
print("n = " + n);
}
break i continue
for (i in 1..10) {
if (i == 3) continue;
if (i == 7) break;
print(i);
}
Labeled loops (etykiety)
outer: for (i in 1..5) {
for (j in 1..5) {
if (i * j > 10) {
break outer;
}
print(i, "*", j, "=", i * j);
}
}
outer: for (row in 1..3) {
for (col in 1..3) {
if (col == 2) {
continue outer;
}
print(row, col);
}
}
Loop else
Blok else wykonuje się gdy pętla zakończyła się **bez** break:
let list = [1, 2, 3, 4, 5];
let target = 10;
for (item in list) {
if (item == target) {
print("Znaleziono!");
break;
}
} else {
print("Nie znaleziono!");
}
while (condition) {
} else {
print("Pętla zakończona normalnie");
}
Praktyczne przykłady
let sum = 0;
for (i in 1..100) {
sum = sum + i;
}
print(sum);
for (i in 1..15) {
if (i % 15 == 0) print("FizzBuzz");
else if (i % 3 == 0) print("Fizz");
else if (i % 5 == 0) print("Buzz");
else print(i);
}
fn isPrime(n) {
if (n < 2) return false;
for (i in 2..n) {
if (n % i == 0) return false;
}
return true;
}
💡 Wskazówka
Używaj repeat gdy potrzebujesz prostej pętli N razy. Używaj for-in do iteracji po kolekcjach. Używaj while gdy warunek końca jest złożony.