Explain the difference between while and for loops and give an example of each.

Study for the End of Year 8 Computer Science Test. Prepare with flashcards and multiple choice questions, each with hints and explanations. Get ready for your exam!

Multiple Choice

Explain the difference between while and for loops and give an example of each.

Explanation:
The difference lies in how many times a block of code runs. A while loop keeps repeating as long as a condition is true, checking that condition every time before the next iteration. A for loop repeats a set number of times or over items in a collection, typically using a counter or an iterator. For example, a while loop like while x < 5: x += 1 will keep increasing x until x reaches 5, at which point the condition x < 5 becomes false and the loop stops. A for loop like for i in range(5): print(i) runs five times, with i taking values 0 through 4, then stopping. This matches the idea that while loops respond to a condition, while for loops are used when you know how many iterations you want or when you’re looping over a sequence. Other options mix up these roles or claim sameness across languages, which isn’t accurate.

The difference lies in how many times a block of code runs. A while loop keeps repeating as long as a condition is true, checking that condition every time before the next iteration. A for loop repeats a set number of times or over items in a collection, typically using a counter or an iterator.

For example, a while loop like while x < 5: x += 1 will keep increasing x until x reaches 5, at which point the condition x < 5 becomes false and the loop stops. A for loop like for i in range(5): print(i) runs five times, with i taking values 0 through 4, then stopping.

This matches the idea that while loops respond to a condition, while for loops are used when you know how many iterations you want or when you’re looping over a sequence. Other options mix up these roles or claim sameness across languages, which isn’t accurate.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy