UPI Study › Courses › Programming in C › Free lessons › Lesson 5.3 Free with a free account
The for Loop in C
Programming in C · Chapter 5: Loop Constructs, Control Statements, and Error DiagnosisSection 5.3 · lesson 28 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 do-while Loop →← The while Loop in CNext lesson: The do-while Loop →
In this lesson
Gathering a loop's start, test and step into one header.
- Describe the order in which a for loop runs its three header parts
- Write for loops that count up, count down and count in steps
- Explain the scope of a counter declared in the for header
- Avoid off-by-one errors by matching the start value to the comparison
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 (976 words). Read along, or search it.
Opening Analogy
Start, Finish and Lap Counter Together
Picture a stopwatch card with the start, the finish line and the lap counter printed side by side. Nobody has to hunt for where the race begins. Here's a counting loop written with while. The start is on one line, the test on another, and the step hides at the bottom of the body, where it's easy to forget. The for loop gathers those three pieces into its parentheses, separated by two semicolons. The body holds only the real work. When a loop is about counting, the for loop is the tidy way to write it.
Execution Order
The Update Runs After the Body
Read the header carefully, because its order is the one thing beginners trip over. The three parts share one line, but they don't run from left to right. The initializer runs once. Then the condition is tested. If it's true, the body runs, then the update, and then it's back to the condition. So the update is written before the body, but it runs after it. And i plus plus just means add one to i, from three point three. Build and run it: one to five. A for loop is a while loop, with its housekeeping tidied into the header. It has the same pre-test as while, so a for loop can run zero times too.
Variations
Counting Up, Down and in Steps
You change the direction by changing the three parts. To count up: start low, test with less than or equal, and add. To count down: start high, test with greater than or equal, and subtract, with i minus minus. To count by steps, use i plus equals five, which adds five on each pass. Here, i is declared once, before the loops, so each header just sets it, with no int. Build and run it. Up, down, and in steps of five. Notice what the body never sees: the value that made the condition false. Going up, that's six. Going down, that's zero. And in steps of five, it's twenty-five. None of them is ever printed.
Choosing a Loop
Known Count or Unknown End
So which loop should you pick? Use for when you know how many times to go: five rounds, ten players. Use while when the end depends on something that happens along the way, like a typed zero, or a player choosing Quit.
Quick Check
Starting at Two, Adding Three
Quick check. This loop starts at two, and adds three on each pass, while i is at most eight. What does it print? Pause and predict. It prints two, five, eight. Two is printed before any update, because the initializer starts there. Then five, then eight, which is still at most eight. The next value is eleven, and eleven fails the test, so the body never prints it.
Worked Example
A Score Table With a Header Counter
The arcade board needs a table: the turn, the score, and a ten percent bonus, for turns one to five. This time the loop variable, turn, is declared inside the parentheses. That's allowed since the C99 standard, and it's the usual style now, because the counter belongs to the loop. In older C89 code, the variable had to be declared before the loop. Inside the body, score is a new variable too. It's created fresh on every pass, and gone at the closing brace. Percent five d reserves five spaces for each number, so the columns line up. Build and run it. Five rows, one per pass.
Loop Scope
The Counter Disappears After the Loop
A variable declared in the header lives only inside the loop. That protects you from leftover values, but it also means you can't use the counter afterward. Try it: print the last turn, after the loop has ended. Clang refuses: use of undeclared identifier turn. Past the loop's closing brace, the name no longer exists. If you need the final value, declare the variable before the for, as count forms did, and leave int out of the header. Why a name stops existing outside its braces is the topic of scope, in six point three.
Off-by-One Errors
The Machine That Does Not Exist
The most common loop bug runs one time too many, or one too few. It's called an off-by-one error, and it usually comes from picking the wrong comparison. The arcade has three machines, numbered zero, one and two. Lots of things in C start counting at zero, as arrays will show in seven point one. Start at zero and stop before three: exactly three passes. Run it, and machines zero, one and two are checked. Now Sam, who tests the arcade's programs, changes less than to less than or equal. One extra character. Build and run it again. Checking machine three. Checked four machines. Sam reported that machine three was broken. Priya, who writes the programs, looked at the floor: there is no machine three. The loop invented it. And clang gave no warning at all. The program looks fine. It just makes one pass too many. So count the passes for the smallest case, and test the edge values. A loop that starts at zero runs n times with less than n. One that starts at one runs n times with less than or equal to n.
Quick Check
Starting at One With Less Than Ten
Quick check. Here k starts at one, and the test is k less than ten. Each pass adds one to count. What will count be at the end? Pause and predict. It prints count equals nine. The values of k are one through nine. When k reaches ten, ten is not less than ten, so the loop stops. Ten passes would need either a start at zero, or less than or equal to ten. Mixing a start at one with less than is the classic off-by-one.
Key Takeaways
The for Loop in Review
To sum up. A for loop puts the initializer, the condition and the update in one header. The update is written before the body, but runs after it. A counter declared in the header exists only inside the loop. And off-by-one errors come from mixing up less than and less than or equal. Clang won't warn you, so count the passes.
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 for Loop in C
In what order do the parts of a C for loop run?
When should you use a for loop instead of a while loop?
Can you use a for loop counter after the loop ends?
What is an off-by-one error in a for loop?
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 →