The while Loop Mechanism, Explained with Code Examples

UPI Study › Courses › C++ Programming › Free lessons › Lesson 5.3 Free with a free account

The while Loop Mechanism

C++ Programming · Chapter 5: IterationSection 5.3 · lesson 31 of 84video coming soon

← Dissecting the for LoopNext lesson: The do-while Loop →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

In this lesson

Running until a condition fails.

  • Write a while loop and state the order its parts run
  • Place the update yourself, on every path
  • Build a sentinel loop with a priming read
  • End a loop with a flag; choose while or for

Transcript

Everything said in the video, section by section (1,386 words). Read along, or search it.

Opening Question

Loops When Nobody Knows the Count

A counted loop needs to know how many passes there'll be. Very often, nobody does. Entries arrive until the operator stops typing. A calculation repeats until it's close enough. A queue empties when it empties. The while loop is the shape for all of these. It asks a question before every pass, and keeps going for exactly as long as the answer is yes.

Syntax

Condition, Body, and Asking Again

The syntax is a condition in parentheses and a body, exactly like if. The difference is what happens at the end of the body: control returns to the condition, and asks again. Countdown starts at 3. While it's greater than 0, print it, then subtract 1. After the loop, print liftoff. Test one: countdown is 3, true. It prints 3, and becomes 2. Tests two and three print 2 and 1. Test four: countdown is 0, the condition is false, and the loop ends. Liftoff.

Quick Check

Doubling Loop Prediction

Quick check, on a new loop. n starts at 1, and doubles on every pass, while it's less than 20. How many times is the condition tested, and how many times does the body run? Pause, and predict.

Answer

One More Test Than Passes

Tested six times, and the body runs five. n is 1, 2, 4, 8 and 16 on the passes. At 32, the test fails. There's always one more test than passes, because the last test is the one that fails. Because the test comes before every pass, including the first, a condition false at the outset means the body never runs. That's normal: a loop over empty data should do nothing. Writing a trace like this by hand, one row per pass, is the most reliable way to check a loop you're unsure about.

Common Mistakes

Stray Semicolon and Missing Braces

Two punctuation traps carry over from if. There's no semicolon after the closing parenthesis. Write while n is greater than 0, semicolon, and the loop's entire body is an empty statement. Nothing in the real block ever runs, nothing changes, and the loop never ends. Clang warns about it. And braces belong on every body. Without them, the update line sits outside the loop, and that's precisely the line that must not.

Loop Anatomy

Three Questions Scattered Across a While

Every loop answers three questions: where it starts, when it stops, and what changes each pass. A for loop collects all three into its header, where they're visible together and hard to forget. A while loop scatters them. The initialization is a separate statement before the loop. The test lives in the parentheses. And the update goes somewhere in the body, wherever you put it. Nothing reserves a place, and nothing reminds you. That's the whole character of the while loop. A body that changes nothing is perfectly legal. It simply runs forever, and the symptom appears only when the program is run.

Key Rule

The Body Must Change the Condition

The responsibility fits in one sentence. Something in the body must change what the condition tests, on every path through the body. Read your condition, identify what it depends on, and confirm the body changes that thing. Count less than limit: increase count. Entry isn't done: read a new value into entry. Remaining greater than zero: reduce it by what was used. Not finished: set finished when the ending arrives. A gap against a tolerance: recompute the gap, so it shrinks.

Worked Example

An Update Hidden Inside the If

The phrase, on every path, matters as much as the rest. Here, while index is less than total, the body checks whether the entry is valid. If it is, it prints it and advances the index. But the advance is tucked inside the if, so it runs only on valid passes. Say entry 2 is invalid. It prints 0 and 1, each on its own line, and then it hangs. The condition still holds, the same answer comes back, and nothing ever changes. Move the advance below the if, and every pass moves forward, whether the entry was processed or not. The update is placed deliberately, not wherever it happens to fit.

Sentinel Loop

Priming Read and Update Read

A sentinel-controlled loop reads values until a designated marker arrives. This is the classic use of while, because the number of values is exactly what nobody knows. It needs two reads, and both are essential. The first sits before the loop, so the first test has something to examine. That's the priming read. Then, while the sale isn't minus 1, add it to the total and count it. The second read sits at the end of the body, so each pass supplies the value the next test will look at. It's the loop's update. And notice the marker is never processed. It arrives, the test fails, and the loop ends before the body touches it. Three sales, total 75: the minus 1 is neither added nor counted.

Common Faults

Three Ways Sentinel Loops Fail

This pattern attracts three faults. With no priming read, the first test examines a variable that was never given a value. With no read at the end of the body, the same first value is tested and processed endlessly. And with the read at the start of the body instead, the primed value is skipped. The marker itself gets processed. Same kind of input, 40, 25, then minus 1: two sales, total 24. Choose the marker carefully. Minus 1 is safe for sale amounts, which are never negative, and unsafe for temperatures. When no number is impossible, read text, and use a word such as done.

Flag Loop

A Bool Set by the Body

Sometimes the reason to stop isn't a value in the data, but a situation the body discovers. Perhaps several situations. A flag handles this: a bool that the condition tests, and the body sets. Here, searching starts true. Each pass reads a guess and counts the attempt. If the guess matches, searching becomes false. And if this was the third attempt, searching also becomes false. Two quite different endings, both expressed the same way. The condition stays readable, because it says what the loop is for, not every way it might finish. Adding a third ending later means adding a case, not rewriting the condition.

Comparison

Sentinel Versus Flag Trade-offs

So, sentinel or flag? A sentinel loop ends when a specific value appears in the data. It's best when there's one clear end-marker. Its risk is a marker that real data could also take. A flag loop ends when the body sets a bool. It's best when the stopping reason is found inside the body, or there are several. Its risk: a path that never sets it. Name the flag for the situation: searching, has more data, keep going. Not flag, or done two. And prefer a positive name. Nobody reads while not not-finished correctly at speed.

Choosing

When to Use For or While

Either loop can express anything the other can, so the choice is about which one tells the reader the truth at a glance. A receipt line for each of 12 months: for. The count is known. Read sales until the marker: while. Halve a distance until it's under a tolerance: while, because the arithmetic decides. Every element of a known-size collection: for. Keep prompting until the input is valid: while, because the person typing decides. The short version: if you can state the number of passes before the loop starts, use for. If you can't, use while. A for header with an empty slot is usually a while loop wearing the wrong clothes.

Key Terms

Vocabulary of the While Loop

A few key terms. A while loop tests its condition before every pass, and runs the body for as long as it's true. The condition variable is whatever the condition depends on. The body must change it for the loop to end. A priming read is the read before the loop, so the first test has a value to examine. A sentinel is a marker value that ends the loop, never one real data could take. And a flag is a bool the condition tests and the body sets.

Key Takeaways

Summary and a Game Loop Question

To summarize. A while loop tests, runs the body, and tests again. Zero passes is a normal outcome. The update is your responsibility, and it must run on every path through the body. Sentinel loops read twice: before the loop, and at the end of the body. Flags handle stopping reasons found inside the body. If the count is known, use for. If not, use while. Here's something to think about. A game loop ends when the player quits, loses the last life, or clears the final level. Which control style suits it, a sentinel or a flag, and why?

About C++ Programming at UPI Study

C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

C++ Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About The while Loop Mechanism

How does a while loop work in C++, and in what order do its parts run?
A while loop tests its condition before every pass, runs the body if the condition is true, then returns to the condition and tests again. It stops when the test is false. Because the test comes first, a condition that starts false means the body never runs. A loop with n starting at 1 and doubling while n < 20 tests six times and runs five passes.
Why does my while loop never end, and how do I fix it?
A while loop runs forever when nothing in the body changes what the condition tests. Find the variable the condition depends on and make sure the body updates it on every path. An update placed inside an if runs only on some passes, so put it below the if. A semicolon right after while (condition) also creates an empty body and an endless loop.
How do I write a sentinel-controlled while loop with a priming read?
Read the first value before the loop (the priming read), loop while that value is not the sentinel, and read the next value at the end of the body. For example: cin >> sale; while (sale != -1) { total += sale; cin >> sale; }. The sentinel is never processed, because the test fails before the body runs. Skipping either read breaks the loop.
When should I use a while loop instead of a for loop in C++?
Use a for loop when you can state the number of passes before the loop starts, and use a while loop when you can't. Reading sales until a marker, halving a distance until it is under a tolerance, and prompting until input is valid all suit while. A for header with an empty slot is usually a while loop in disguise.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in C++ Programming.

84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

C++ Programming
3 credits · NCCRS
Enroll →