Loop Fundamentals in C, Explained with Code Examples

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

Loop Fundamentals in C

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

← Workshop: Menu-Driven Programs and Grade CalculatorsNext lesson: The while 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

The four parts every C loop shares, and how to trace them.

  • Identify the initializer, condition, body and update of a loop
  • Trace a loop with a table of variable values
  • Explain why the condition is checked one more time than the body runs
  • Recognize how a missing or wrong-way update causes an infinite loop

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 (958 words). Read along, or search it.

Opening Problem

Five Hundred Machines, One Loop

Opening time at the Starlight Arcade: five hundred game machines, and each one needs a token dropped in. Priya, who writes the arcade's programs, could type five hundred printf lines. Three are annoying. Five hundred is silly. And if the number of machines changes tomorrow, every one of those lines has to change by hand. What she really wants is to say: do this, over and over, until the job is done. And let the computer count. That idea is a loop. Every loop in C is built from the same four parts, and once you know them, every loop reads the same way.

Definition

Loops, Iterations and Passes

A loop is a piece of code that the computer runs again and again. One trip through it is called an iteration, or a pass. Loops are all over the arcade. Count the players waiting in line. Add up every score on the board. Ask a player for a number until they type a good one. Show the menu again after every choice. Underneath, they share one shape: set up, ask a question, do some work, change something, and ask again.

The Four Parts

Initializer, Condition, Body and Update

Picture a child feeding marbles down a toy ramp. First, count the pile. That's the initializer: it sets the starting value, once. Then a question: is there still a marble in the pile? That's the condition, a true-or-false test, asked before every pass. Putting one marble on the ramp is the body, the work to repeat. One fewer marble in the pile is the update. The update is easy to forget, and it matters most: it changes something, so the loop moves toward its end. After the initializer, the computer goes around a circle: the condition, the body, the update, and back to the condition. Only a false answer from the condition lets it leave.

First Example

Dropping Three Tokens With while

Here are the four parts in a real C program, first loop dot c. It uses the while statement, which you'll study properly in five point two. C keeps going around while the condition in parentheses is true. The initializer is line four: tokens starts at one. It sits outside the braces, because it should run once, not on every pass. The condition is on line six: tokens is less than or equal to three. Line seven is the body: it prints which token is dropping. And line eight is the update: tokens goes up by one. Build it with clang, run it, and the count climbs: one, two, three. Then the condition answers false, and Done prints. A good habit: when you read a loop, point at each of the four parts and name it. If one is missing, you've found the bug before running anything.

Tracing

Playing Computer With a Table

How do you know what a loop will do before you run it? You play computer. This one adds up one, two, three and four. Make a table: a column for each variable, and a row for each time the condition is checked. Total starts at zero, and i at one. First check: i is one, and one is at most four. True. So the body runs: total becomes one, and i becomes two. Second check: two is at most four, true. Total becomes three, and i becomes three. Third check: three, still true. Total becomes six, and i becomes four. Fourth check: four is at most four, because they're equal. True. Total becomes ten, and i becomes five. Fifth check: is five at most four? No. False, so the loop ends, and the program moves on to the printf. Build and run it to confirm: total is ten, and i is five. Now count. The body ran four times, but the condition was checked five times. The last check is the one that says stop. That one extra check is why tracing catches a loop that runs one time too many, or one too few.

Quick Check

Subtracting Two Each Pass

Quick check, with a new loop. Here n starts at ten, total starts at zero, and each pass takes two away from n. Trace it with a table. What does it print? Pause and predict. It prints total equals eighteen, n equals six. Ten passes the test, so ten is added. Eight passes too, so total reaches eighteen. Then n becomes six. Is six greater than six? No. So the loop ends after two passes and three checks. Twenty-four would need six to pass the test as well. It doesn't: the test is greater than, not greater than or equal.

Common Mistake

The Forgotten Update

Now Sam, who tests the arcade's programs, writes his first loop. He forgets one part: the update. It compiles without a single warning. Run it, and the screen fills up with dropping token one, again and again. Nothing ever changes tokens, so the condition gives the same answer every time. That's an infinite loop. No crash, no error. It just keeps going. In a terminal, Control C stops it. Priya looks at the loop, points at the update, and finds it blank. A loop needs all four parts, and this is the one that makes it end. There's a second way to build the same bug: an update that moves the wrong way. Taking a token away, while waiting for the count to climb past three. So before you run any loop, ask one question: does each pass move me closer to a false condition?

Key Takeaways

Loop Parts in Review

To sum up. Every loop has four parts: an initializer, a condition, a body, and an update. The initializer runs once. Then the loop circles through condition, body and update, until the condition is false. Trace a loop with a table, one row per check. The condition is checked one more time than the body runs. And if no pass moves the loop toward a false condition, it never ends.

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

What are the four parts of a loop in C?
Every loop has an initializer, a condition, a body and an update. The initializer sets the starting value once. The condition is a true-or-false test asked before each pass. The body is the work to repeat, and the update changes something so the loop moves toward its end. After the initializer, the loop cycles through condition, body and update until the condition is false.
How do you trace a loop by hand?
Make a table with a column for each variable and a row for each time the condition is checked. For total = 0 and i = 1, with the test i <= 4 and a body that adds i to total and then adds 1 to i, the rows show total reaching 1, 3, 6 and 10. On the fifth check i is 5, the test fails, and the loop ends.
Why is a loop condition checked one more time than the body runs?
The final check is the one that comes out false and ends the loop. A loop whose body runs four times checks its condition five times: four true answers, then one false. Counting that last check during a trace is what reveals a loop that runs one time too many or one too few, because the boundary comparison decides whether an extra pass happens.
What causes an infinite loop in C?
An infinite loop happens when no pass moves the condition toward false. The usual cause is a forgotten update, so the variable in the condition never changes. Another is an update that moves the wrong way, such as subtracting while waiting for a count to climb. Such code can compile without warnings and simply keeps running. In a terminal, Control-C stops it.

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 →