The do-while Loop in C, Explained with Code Examples

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

The do-while Loop

Programming in C · Chapter 5: Loop Constructs, Control Statements, and Error DiagnosisSection 5.4 · lesson 29 of 786 min · free with a free account

← The for Loop in CNext lesson: Interrupting Normal Flow: break, continue, and goto →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

In this lesson

A C loop that runs its body first and tests afterward.

  • Explain why a do-while body always runs at least once
  • Compare the fewest passes of while and do-while loops
  • Write a do-while loop that asks again until the input is in range
  • Place the required semicolon after a do-while condition

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

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

Opening Analogy

One Free Sample, Then a Question

At the Starlight Arcade's taste-test booth, every visitor gets one free sample first. Only after tasting does the booth ask: would you like another? Nobody is asked before they've tried anything. The do-while loop works like that booth. It does its work first, and asks its question afterward. So its body is guaranteed to run at least once. And that makes it perfect for one job in particular: asking for input until the answer is good.

Syntax

A Post-Test Loop

In a while loop, the test is at the top. In a do-while loop, it moves to the bottom, after the closing brace. C runs the body once, and only then looks at the condition. If it's true, C jumps back up to the word do, and runs the body again. If it's false, the loop is over. That makes do-while a post-test loop: the test comes after the body. While and for are pre-test loops. And notice the semicolon after the condition. A do-while is one complete statement, so it ends with a semicolon.

Comparison

Zero Passes Versus One Pass

To see the difference, here are both loops with the same starting value: a player with zero tokens. Each loop counts how often its body runs. The while loop asks first, hears no, and skips its body. The do-while loop runs its body once, before any question. Then it hears no, and stops. Build and run it. While ran zero times. Do-while ran one time, even though the condition was false from the start. That one guaranteed pass is the whole point of do-while.

Worked Example

Play Another Round

Some jobs must happen once, no matter what. A game round is one: the player always gets a first round, and only then is asked about another. With while, you'd have to fake an answer first, like setting again to one, just to get into the loop. Do-while needs no pretending. The variable again is read at the end of the first pass, exactly when it's first needed. Build it, run it, and answer one, one, then zero. Three rounds. The first came before any question, and two more because the answer was one each time. The zero made the condition false, and the loop ended there.

Quick Check

Printing Before Any Test

Quick check. In this loop, n starts at zero, and each pass prints n, then takes three away. The loop repeats while n is greater than zero. What does it print? Pause and predict. It prints a single zero. The body runs before any test, so zero is printed, and n becomes minus three. Then the test: is minus three greater than zero? No. So there's no second pass, and minus three is never printed. A while loop with the same test would print nothing at all, because zero fails the test before the first pass.

Input Validation

Repeat While the Answer Is Wrong

The most useful job for do-while is input validation: checking that what the user typed is acceptable. You can't check an answer before you've asked for it, so the question has to come first. That's a body-first loop. Priya, who writes the arcade's programs, needs a difficulty level from one to five. Read her condition aloud: repeat while the level is below one, or above five. It describes what's wrong with an answer. A common slip is to write what's right instead. That loop would stop on bad answers, and repeat on good ones. Build it, run it, and type nine, then three. Nine is refused, with a message that says why. A silent re-ask would feel broken. Then three is accepted, and the game starts on level three. One caution: this loop expects a number. A typed letter could make it spin forever. The workshop at the end of this chapter makes it safe.

Quick Check

Three Tries for a Level

Quick check. Sam, who tests the arcade's programs, runs it and types zero, then twelve, then four. How many times is he asked for a level? Pause and predict. He's asked three times. Zero is below one, so it's refused. Twelve is above five, so it's refused too. Four is in range, so the condition is false, and the loop ends. Sam's next question: if I typed a good number first, would it still ask once? It always asks once. That's the point of do-while.

Common Mistake

The Missing Semicolon After while

One slip to watch for: the semicolon after the condition. A while loop at the top has none, but a do-while ends with one. Leave it out, and clang stops: expected semicolon after do-while statement. It even shows where the semicolon belongs. Put it back, build again, and the loop counts down: three, two, one, and then Done.

Choosing a Loop

Must the Body Run Once

Both loops can do the same work, if you try hard enough. The question to ask is: must the body run at least once? A while loop tests before each pass, so its fewest passes is zero. A do-while tests after, so its fewest is one. And only the do-while has a semicolon after its condition. Work that might be empty, like reading until a sentinel, suits while. Work that must happen once, like asking and checking an answer, suits do-while.

Key Takeaways

The do-while Loop in Review

To sum up. A do-while runs its body first, and tests its condition after each pass. So its body always runs at least once. That makes it the natural loop for asking, checking, and asking again. And it ends with a semicolon after the condition.

About Programming in C at UPI Study

Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. 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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
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

Programming in C 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 while and do-while in C?
A while loop tests its condition before each pass, so its body can run zero times. A do-while loop runs its body first and tests afterward, so its body always runs at least once. If n starts at 0 and the test is n > 0, a while loop prints nothing, while a do-while that prints n and subtracts 3 prints 0 once before stopping.
What is the syntax of a do-while loop in C?
Write do, then the body in braces, then while with the condition in parentheses, and end with a semicolon, as in do { n--; } while (n > 0);. The semicolon is required because the whole do-while is one statement. If it is missing, clang stops with an error saying a semicolon is expected after the do-while statement. A plain while loop has no semicolon after its condition.
How do you use do-while to validate user input in C?
Ask for the value inside the do body and repeat while the answer is unacceptable. For a difficulty level from 1 to 5, the loop can end with while (level < 1 || level > 5);. Typing 0, then 12, then 4 asks three times. Print a message for each refused answer, because a silent re-ask feels broken. A typed letter needs extra handling with scanf's return value.
Why does my do-while validation loop repeat on good input?
The condition probably describes a good answer instead of a bad one. A do-while repeats while its condition is true, so the condition must say what is wrong, such as level < 1 || level > 5. Writing level >= 1 && level <= 5 reverses the behavior: the loop stops on bad answers and asks again after good ones. Read the condition aloud as repeat while this is wrong.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) 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 Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 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 Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 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 Programming in C.

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

Programming in C
3 credits · NCCRS
Enroll →