Beginner Topic 11 of 54 Programming Fundamentals
While Loops
Loops that test a condition before each iteration.
How it works
A while loop checks its condition before every iteration and may run zero times, while a do-while loop checks after the body and therefore always runs at least once. The loop continues until something inside the body changes the state that the condition depends on. While loops suit situations where the number of iterations is not known in advance.
Step-by-step walkthrough
- The condition is tested first, so the body may never run.
- If it is true the body executes.
- The body must change something that affects the condition.
- Forgetting that change creates an infinite loop.
- When the test finally fails the loop is skipped over.
Where it is used
Reading until end of file, waiting for a user to quit, polling a resource until it is ready, running Newton-style convergence loops and implementing game or server main loops all use while loops.
Common pitfall
Forgetting to update the variable in the condition produces an infinite loop. Conditions that depend on external state can hang if it never changes, so add timeouts or maximum attempt counts. Mixing up while and do-while changes whether the body runs for empty input.
Where it fits in the course
While Loops is topic 11 of 54 in Programming Fundamentals, rated Beginner. It follows For Loops. The next topic is Functions.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is While Loops?
Where do people use While Loops?
What is the most common mistake with While Loops?
What should I learn before this topic?
How can I practice it?
Is While Loops hard to learn?
How long does it take to learn While Loops?
Which topics are related to While Loops?
What should I study after While Loops?
Related topics
- For Loops (Programming Fundamentals)
- Functions (Programming Fundamentals)
- Loops (Programming Fundamentals)
- Parameters and Arguments (Programming Fundamentals)