While Loops
Learn how to execute iterative logic dynamically using condition-controlled while loops.
Basic While Loop
The while loop continues executing its block as long as the conditional expression evaluates to truthy:
let count: int = 1;
while count <= 5 {
print("Count:", count);
count += 1;
}
Practical Algorithm: Prime Checker with While
Here is an example demonstrating a while loop used inside a prime-checking function:
fun is_prime(n: int) -> bool {
if n <= 1 {
return false;
}
let divisor: int = 2;
while divisor * divisor <= n {
if n % divisor == 0 {
return false;
}
divisor += 1;
}
return true;
}
print(is_prime(29)); // true
print(is_prime(30)); // false