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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Interrupting Normal Flow: break, continue, and goto →← The for Loop in CNext lesson: Interrupting Normal Flow: break, continue, and goto →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
What is the syntax of a do-while loop in C?
How do you use do-while to validate user input in C?
Why does my do-while validation loop repeat on good input?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →