The while Loop in C, Explained with Code Examples

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

← Loop Fundamentals in CNext lesson: The for Loop in C →

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

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.

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 while Loop in C

How does a while loop work in C?
A while loop tests its condition before every pass, including the first. If the condition is true, the body runs once and C jumps back to the test; if it is false, C skips the body and continues after the closing brace. For example, while (tokens > 0) with tokens-- in the body runs three times for three tokens and checks the condition four times.
Can a while loop run zero times?
Yes. Because the condition is tested before the body, a while loop whose condition is false at the start never runs its body. A player who starts with zero tokens plays no games, which is the correct result, not an error. Programmers call this the zero-iteration case. After writing a while loop, ask what happens if the condition is false the first time.
What is a sentinel value in a while loop?
A sentinel is a special input value that can never be real data and signals the end of input, such as 0 when no player spends zero tokens. Read once before the loop so the first test has a value, and again at the bottom of the body as the update. Typing 4, 6, 0 and 9 counts two players and 10 tokens; the 9 is never read.
Why does a while loop need braces around its body?
Without braces, only the first statement after the condition belongs to the loop. If the update, such as tokens--, is the second statement, it ends up outside the loop, the condition never changes, and the loop repeats forever. Clang compiles that version without a warning. Braces around every while body, even a one-line body, make clear exactly which statements repeat.

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 →