UPI Study › Courses › Programming in C › Free lessons › Lesson 5.2 Free with a free account
The while Loop in C
Programming in C · Chapter 5: Loop Constructs, Control Statements, and Error DiagnosisSection 5.2 · lesson 27 of 787 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: The for Loop in C →← Loop Fundamentals in CNext lesson: The for Loop in C →
In this lesson
Testing before every pass with C's while loop.
- Explain how a while loop tests its condition before every pass
- Recognize the zero-iteration case as correct behavior
- Read input until a sentinel value with a read before the loop and one at the bottom
- Build a menu that repeats until the user chooses Quit
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 (957 words). Read along, or search it.
Opening Analogy
The Bouncer Asks Every Time
A bouncer stands at the door of the Starlight Arcade, and asks everyone one question: do you have a token? Yes, and in you go. Come back out, and the bouncer asks again. The moment the answer is no, the door stays shut. That includes the very first time. Someone who arrives with no tokens never gets in at all. The while loop is that bouncer. It asks first, every single time, and it never runs its body when the answer is no.
Syntax
A Pre-Test Loop
The while statement is short: the word while, a condition in parentheses, and a body in braces. The condition is a pre-test. C tests it before the body, on every pass. If it's true, the body runs once, and C jumps back up to the test. If it's false, C skips the whole body, and carries on with the line after the closing brace.
Worked Example
Playing Until Tokens Run Out
Here's a player with three tokens, who plays until they run out. The condition, tokens greater than zero, is on line seven. The update, one fewer token, is on line nine. It's what eventually makes the condition false. Build and run it. Three games, with three, two and one tokens left before each. So the condition was checked four times. Three, two and one said yes. Zero said no. Notice the braces around the body. Always use them, even when the body is one line. Take them away, and only the first statement after the condition belongs to the loop. The update now sits outside it. Tokens would never change, and the printf would repeat forever. And clang compiles that version without a single warning. Braces make the body unmistakable.
Zero Iterations
When the Body Never Runs
Because the test comes first, a while loop might never run its body at all. Start the player with zero tokens, and run it again. No game line at all. The very first check, zero greater than zero, was false. So C jumped over the body, straight to the last printf. And plays stayed at zero, which is exactly right. A player with no tokens should play no games. Programmers call this the zero-iteration case. It isn't an error. It's the right answer when there's no work to do. So when you finish a while loop, ask: what if the condition is false the first time? If the program still does the right thing, the loop is safe.
Sentinel Loop
Reading Until a Zero Is Typed
Sometimes nobody knows how many passes are needed. How many players will come to the token counter today? Then the loop has to end when something outside the program changes, like a number someone types. A common trick is a sentinel: a special value that can never be real data. It means, that was the last one. Here, it's zero, because no player spends zero tokens. The pattern has a twist. Read once before the loop, so the first test has something to look at. Then read again as the last line of the body. That second read is the update: it changes the value the condition looks at. Build it, run it, and type twelve, seven, thirty, and then zero. Three players, forty-nine tokens. The zero ended the loop, before it could be counted as a player. Forget the second scanf, and spent never changes, so the loop never ends. And if zero were a legal answer, you'd need another sentinel, such as minus one. This loop also trusts the player to type numbers. Checking what scanf really read comes in the workshop at the end of this chapter.
Quick Check
Input After the Sentinel
Quick check. Same program, new typing: four, then six, then zero, then nine. How many players, and how many tokens, does it report? Pause and predict. It prints two players, ten tokens. Four and six are added up. Then the zero is the sentinel, so the loop ends right there. The nine is never read at all. The program has already stopped asking. Nineteen would mean the loop kept reading past the zero. A sentinel ends the input, wherever it appears.
Menu Loop
Repeating Until the Player Quits
Every arcade machine shows a menu, and keeps showing it until the player picks Quit. That's a while loop too. Priya, who writes the arcade's programs, built this one. The condition says: the choice isn't Quit yet. Inside, an else-if chain from four point five decides what each choice does. Choice starts at zero, a value that isn't Quit, so the first test is true, and the menu shows at least once. Run it. The player picks one, and plays a game. Then seven. That isn't on the menu, so the final else answers it, and the loop goes around again. Then three. Thanks for visiting prints first, because the body finishes its pass before the condition is looked at again. Only then is the condition false, and the loop ends. Sam, who tests the arcade's programs, typed nine, zero and seven in a row. Each time, the menu came back. Priya's answer: thank the else at the bottom.
Quick Check
Starting the Choice at Quit
Quick check. Sam changes one thing: choice now starts at three instead of zero. He builds it and runs it. What happens? Pause and predict. Nothing prints, and the program ends. This is the zero-iteration case again. The very first test asks: is three not equal to three? False. So the whole body is skipped, menu and all. The thanks line can't print either: it's inside the body. Here, starting at zero is what lets the player in.
Key Takeaways
The while Loop in Review
To sum up. A while loop tests its condition before every pass, including the first. So its body can run zero times, and that's often exactly right. To read until a sentinel, read once before the loop and again at the bottom of the body. And a menu repeats while the choice isn't Quit.
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 while Loop in C
How does a while loop work in C?
Can a while loop run zero times?
What is a sentinel value in a while loop?
Why does a while loop need braces around its body?
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 →