Junior — Middle
What are the differences between for and while loops in organizing repetitive operations in programming?
sobes.tech AI
Answer from AI
Main differences between for and while loops:
- for is usually used when the number of repetitions is known or when iterating over a collection. The for loop includes initialization, condition, and step in one line.
- while is suitable when the number of repetitions is unknown in advance, and the loop continues as long as the condition is true.
Example of for:
for (i in 1..5) {
println(i)
}
Example of while:
var i = 1
while (i <= 5) {
println(i)
i++
}
Thus, for is convenient for iterating over ranges or collections, while is suitable for loops with conditions depending on dynamic factors.