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
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 while Loop in C →← Workshop: Menu-Driven Programs and Grade CalculatorsNext lesson: The while Loop in C →
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.
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 Loop Fundamentals in C
What are the four parts of a loop in C?
How do you trace a loop by hand?
Why is a loop condition checked one more time than the body runs?
What causes an infinite loop in C?
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 →