The do-while Loop, Explained with Code Examples

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

The do-while Loop

C++ Programming · Chapter 5: IterationSection 5.4 · lesson 32 of 84video coming soon

← The while Loop MechanismNext lesson: Nested Iteration →

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

In this lesson

Execute first, check later.

  • Write a do-while loop, including its final semicolon
  • Explain test-after semantics and the guaranteed pass
  • Build a menu loop and a read-then-check retry
  • Avoid the scope trap; choose among three loops

Transcript

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

Opening Question

When Deciding After Acting Makes Sense

The two loops met so far both decide before they act. If the condition is false at the start, the body never runs at all. Some tasks are the other way round. You can't ask whether the user wants to continue before showing them anything. And you can't check whether a value is acceptable before reading it. For those, C plus plus provides a loop that runs the body first, and asks afterward. It comes with a guaranteed first pass, and one piece of punctuation that catches everybody once.

Core Idea

Test-Before Versus Test-After Loops

Both loops so far are test-before loops. The condition is examined, and only if it holds does the body run. It becomes the wrong shape whenever the body itself produces the information the condition needs. A menu has to be shown before the choice can be tested. On the left, the while loop tests first. If the test is false, it goes straight out, so the body may run zero times. On the right, the do-while loop runs the body first, and then tests. True goes back to the top. So the body always runs at least once. The same parts, in two orders. The position of the test is the entire difference.

Syntax

The Shape of a do-while Statement

Here's the shape. The keyword do, then the body in braces, then while, the condition in parentheses, and a semicolon. The word do marks the start of the body. Nothing is decided there. The braces hold the statements that repeat. The condition is evaluated after each pass. If it's true, control returns to the top of the body. If false, the loop ends. And the semicolon ends the whole statement. It's required. Omit it, and the build fails. Clang points right at the gap, though some compilers flag the next line.

Why It Works

Why the Semicolon Is Required

Why does this loop need a semicolon, when an ordinary while doesn't? An ordinary while ends with its body, and a block in braces is already a complete statement. A do-while ends with its condition, and a condition in parentheses isn't a statement on its own. The semicolon completes it. Watch for the opposite slip too. A semicolon straight after do ends the statement there. The compiler then expects while, and the build fails.

Quick Check

Tracing Two Loops With Count at 10

The condition isn't examined until the body has already run, so the body always executes at least once. That's the whole point. Here, count starts at 10, already past the limit of 5. Both loops have the same condition. Quick check: what does each loop print? Pause, and trace both.

Answer

Zero Passes Versus One Pass

The while version tests 10 less than 5, finds it false, and never enters the body. It prints nothing. The do-while version runs the body first, printing 10, and making count 11. Then it tests 11 less than 5, finds it false, and stops. One value printed. State it as a rule, and it stops being surprising. A test-before loop runs its body zero or more times. A test-after loop runs it one or more times. If zero passes is a legitimate outcome for your task, this is the wrong loop.

Worked Example

A Menu That Runs Until Exit

The menu is the use this loop was made for. A menu has to be displayed before anyone can choose from it. Whether to display it again depends on what they chose, so the decision belongs at the bottom. The body prints three options, and reads the choice. The code that acts on the choice goes in the middle. The loop repeats while the choice isn't 3, the agreed exit choice. After the loop, it says goodbye. Run it with the choices 1, 2, then 3. The menu appears three times, and the loop leaves on the third.

Walkthrough

How the Menu Cycle Repeats

The cycle goes: show the menu, read the choice, carry it out, then ask whether it was the exit choice. Every pass ends by asking the same question, and only one answer leaves. The exit value is decided once, and written in only two places: the printed menu, and the condition. So they can't drift apart. And the choice variable is declared above the loop, not inside it, for a reason we'll come to with the faults. Without do-while, a test-before loop needs an artificial starting value that makes its condition true, or the whole menu duplicated before the loop.

Second Use

Rereading Input Until It Is Valid

The second common use has the same structure, and the same justification. You can't judge a value you haven't yet read, so the reading comes first, and the judgment follows. The body prompts for units consumed, from 0 to 5000, and reads them. It repeats while units is below 0, or above 5000. Try minus 5, then 9000, then 120. The first two are refused, and the third is accepted. Past the loop, every statement can rely on the value being in range. That removes a condition from everything downstream. This is the shape, not the whole job. Letters typed where a number was expected put the input stream in a failed state, which is covered separately.

Common Mistakes

Faults Specific to do-while

Here are the faults specific to this loop. A missing final semicolon fails the build. Some compilers report it on the line after the loop. If an error points at a line that looks fine, check the line above. A semicolon after do also fails the build, because while must come next. A variable declared inside the body is unknown in the condition. A condition that never becomes false repeats the same prompt forever. If nothing is read inside the body, it runs forever, silently. And finally, using it where zero passes is valid. An empty list still gets processed once, and a total is printed for no data. Use a test-before loop instead.

Scope Trap

Declaring the Variable Inside the Body

That scope fault deserves a closer look. Here, choice is declared inside the body, read, and then tested in the condition. It doesn't build. A variable declared inside the body exists only until the closing brace, and the condition sits after that brace. By the time it's evaluated, the name is gone. This trap is unique to this loop, because it's the only one whose test lives outside the block it controls. Declare the variable above the loop. That fixes the build, and lets you use the value afterward.

Comparison

For, While, and do-while Side by Side

Here are all three forms, compared on the points that decide a choice. For and while test before each pass, so their minimum is zero passes. Do-while tests after each pass, so its minimum is one. And only do-while ends with a semicolon after the condition.

Decision Guide

Two Questions to Pick a Loop

Two questions choose the form. First, do you know how many passes there'll be before starting? If yes, use for. If not, is doing it zero times a valid outcome? If yes, use while. If no, because one pass is certain, use do-while. Any of the three can do any job. The question is which one says what you mean. Do-while is the least used of the three, and that isn't a criticism. When a task does guarantee a first pass, using it says so. Running the body at least once was intended, not an accident of the starting values.

Key Terms

Vocabulary for Loop Testing

A few key terms. A do-while loop evaluates its condition after each pass through the body. A test-before loop may run its body zero times. A test-after loop always runs it at least once. The exit choice is the agreed menu value that ends the loop. And the retry shape reads a value, and repeats while it's unacceptable.

Key Takeaways

Summary and a Closing Puzzle

To summarize. A do-while runs the body, then tests, so it always makes at least one pass. It ends with a required semicolon. Menus, and read-then-check retries, are its natural uses. Declare any variable the condition needs above the loop. And if zero passes is valid, use a test-before loop. Here's something to think about. Given n equal to 7, what does a while loop testing n less than 3 print? And what does the do-while version, with the same condition and body, print?

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 do-while Loop

What is the difference between a while loop and a do-while loop in C++?
A while loop tests its condition before each pass, so its body can run zero times, while a do-while loop runs the body first and tests afterward, so it always runs at least once. With count starting at 10 and the condition count < 5, a while prints nothing and a do-while prints 10 once.
Why does a do-while loop need a semicolon at the end in C++?
A do-while ends with its condition, and a condition in parentheses is not a complete statement, so the semicolon finishes it: do { ... } while (x < 5); Leaving it out causes a build error, and some compilers report it on the next line. A semicolon right after do also fails, because while must come next.
When should I use a do-while loop instead of a for or while loop?
Use a do-while when at least one pass is certain, such as a menu that must display before the user can choose, or input that must be read before it can be checked. If you know the pass count, use for. If zero passes is valid, use while. Otherwise, choose do-while.
Why does my do-while loop say the variable in the condition is not declared?
The variable was most likely declared inside the loop body, and it goes out of scope at the closing brace, before the condition is evaluated. The condition sits after that brace, so the name no longer exists. Declare the variable above the loop, for example int choice; before do, and the code will build and the value stays usable afterward.

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 →