A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

While Loops

College Depth 73 in the knowledge graph I know this Set as goal
685topics build on this
323prerequisites beneath it
See this on the map →
Comparison Operators and Boolean TestsConditional Statements+2 moreDo-While Loops and Post-Test IterationFor Loops+4 more
while iteration loops control flow termination

Core Idea

A while loop repeatedly executes a block of code as long as its condition remains true. Before each iteration the condition is evaluated; when it becomes false the loop exits and execution continues after the loop body. The loop body must eventually cause the condition to become false, or the loop runs forever (an infinite loop). While loops are best used when the number of iterations is not known in advance.

How It's Best Learned

Trace loops by hand, updating a variable table after each iteration. Deliberately create an infinite loop, observe the behavior, and fix it. Implement classic examples: countdown, sum of digits, user input validation.

Common Misconceptions

Explainer

You already understand conditional statements — the idea that a program can check a condition and decide what to do. A while loop extends this idea by adding repetition: instead of checking the condition once, the program checks it *before every iteration* and keeps executing the loop body as long as the condition remains true. The structure is `while (condition) { body }`. The computer evaluates the condition; if true, it runs the body, then goes back and evaluates the condition again. This cycle repeats until the condition is false, at which point the loop exits and the program continues with whatever comes after.

The critical design requirement is that something inside the loop body must eventually make the condition false. If nothing changes the variables involved in the condition, the condition stays true forever and the loop never exits — this is an infinite loop, and it is one of the most common bugs beginners encounter. Typically, the loop body updates a counter, advances through a data structure, or receives new input. For example, in a countdown loop, you decrement a counter each iteration: `while (count > 0) { print(count); count = count - 1; }`. The counter decreases each time, eventually reaching zero, at which point `count > 0` is false and the loop ends.

While loops are the right tool when you do not know in advance how many iterations you need. Reading user input until they type "quit," searching a list until you find a match, or repeatedly halving a number until it drops below a threshold — in all these cases, the number of repetitions depends on data you do not have until the program is running. This distinguishes while loops from for loops (which you will learn next), where the iteration count is typically known or bounded at the start.

One subtle point: the condition is checked only at the top of each iteration, not continuously during the body. If the condition becomes false partway through the body, the rest of the body still finishes executing before the loop checks again. This means a while loop always completes its current iteration in full. Understanding this timing is essential for avoiding off-by-one errors — the most common mistake is using `<` when you meant `<=` (or vice versa), causing the loop to run one too many or one too few times. When in doubt, trace through the first two and last two iterations by hand, tracking every variable, to verify your loop does exactly what you intend.

Practice Questions 5 questions

Prerequisite Chain

Understanding ZeroThe Number ZeroCounting to FiveCounting to 10Counting to 20Counting a Set of Objects Up to 20Cardinality: The Last Number CountedMatching Numerals to QuantitiesSubitizing Small QuantitiesAddition Within 10Number Bonds to 10Addition Within 20Doubles and Near DoublesDoubles Facts Within 10Near Doubles Facts Within 20Mental Math Strategies for AdditionMental Math: Adding and Subtracting TensAddition Within 100Repeated Addition as MultiplicationMultiplication as Equal GroupsMultiplication: ArraysBasic Multiplication Facts (0s, 1s, 2s, 5s, 10s)Multiplication Facts Within 100Division as Equal SharingDivision as Grouping (Measurement Division)Division: Grouping (Repeated Subtraction) ModelDivision: Fair Sharing ModelDivision as Equal SharingDivision as GroupingBasic Division FactsDivision Facts Within 100Multiplication and Division Fact FamiliesRelationship Between Multiplication and DivisionDivision Facts as Inverse of MultiplicationRemainders and Quotients in DivisionDivision Word ProblemsMulti-Step Word ProblemsSolving Multi-Step Word ProblemsMultiplication Word ProblemsDivision Word ProblemsIntroduction to Long DivisionFactors and MultiplesPrime and Composite NumbersEquivalent FractionsRelating Fractions and DecimalsDecimal Place ValueIntegers and the Number LineComparing and Ordering IntegersAbsolute ValueAdding IntegersSubtracting IntegersMultiplying IntegersIntroduction to ExponentsOrder of OperationsInteger Order of OperationsVariable ExpressionsThe Distributive PropertyVariables and Expressions ReviewIntroduction to PolynomialsAdding and Subtracting PolynomialsMultiplying PolynomialsFactorialPermutationsCombinationsCounting Principles: Addition and Multiplication RulesIntroduction to Graph TheoryPropositional Logic FoundationsLogical EquivalencesBoolean AlgebraBoolean Type and Truth ValuesComparison Operators and Boolean TestsLogical Operators and Boolean AlgebraConditional StatementsWhile Loops

Longest path: 74 steps · 323 total prerequisite topics

Prerequisites (4)

Leads To (6)