Opening the book…
A common beginner question is: How do I know whether to use a while loop or a for loop?
|
Question |
Recommended Loop |
|
Do I know exactly how many times the loop should run? |
Use a for loop. |
|
Am I looping through all elements of an array? |
Usually use a for loop. |
|
Am I asking the user for input until the input is valid? |
Usually use a while loop. |
|
Am I repeating until some condition changes? |
Use a while loop. |
|
Am I searching until I find something? |
Either can work; a for loop with break is common. |
Use for when you know the number of repetitions. Use while when you know the condition for stopping.
This page titled 6.9: while Loops vs. for Loops was last modified on Tue, 30 Jun 2026 02:11:42 GMT and is shared under a CC BY-NC-SA license and was authored, remixed, and/or curated by Zara Noroozi.
The book could not be loaded just now.