The for Loop in C, Explained with Code Examples

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

← The while Loop in CNext lesson: The do-while Loop →

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

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.

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

In what order do the parts of a C for loop run?
The initializer runs once, then the condition is tested; if it is true, the body runs, then the update, and control returns to the condition. So the update is written before the body but runs after it. A for loop is a while loop with its housekeeping moved into the header, and like while, it tests first, so it can run zero times.
When should you use a for loop instead of a while loop?
Use a for loop when you know how many passes you need, such as five rounds or ten players. Use a while loop when the end depends on something that happens along the way, such as the user typing a sentinel value or choosing Quit. Both can do the same work, so the choice is about which one states the loop's purpose most clearly.
Can you use a for loop counter after the loop ends?
Not if it was declared in the header. A counter declared in for (int turn = 1; turn <= 5; turn++) exists only inside the loop, so a later printf of turn fails with use of undeclared identifier. To keep the final value, declare int turn before the loop and leave int out of the header. Declaring the counter in the header has been allowed since C99.
What is an off-by-one error in a for loop?
An off-by-one error makes a loop run one time too many or one too few, usually because of the wrong comparison. With machines numbered 0 to 2, for (i = 0; i < 3; i++) checks three machines, but i <= 3 invents a fourth. A loop starting at 0 runs n times with i < n, and one starting at 1 runs n times with i <= n.

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 →