Loops

Is for each loop same as do while loop?

If they were the same, what would be the point of having them exist as separate structures?

Your question is a bit like asking whether a lemon is the same as a lime. They’re both citrus fruit, so what’s the difference, right?

A for each loop will run the loop code block once for every item in a pre-determined set; whether that’s a range of numbers, or a list/array, is up to you. Once it’s got to the end of the set, the loop terminates (if it hasn’t been broken out of previously).

A do while loop will run the loop code block at least once, and then continue to run whilst a given condition is true. If the condition never becomes false, the loop will run indefinitely.

1 Like