UPI Study › Courses › C++ Programming › Free lessons › Lesson 5.1 Free with a free account
Counter-Based Iteration
C++ Programming · Chapter 5: IterationSection 5.1 · lesson 29 of 84video coming soon
← The Rationale Behind LoopsNext lesson: Dissecting the for Loop →
In this lesson
The for loop and how it operates.
- Name the three sections of a for loop and their jobs
- State the order they run in, and how often
- Count up, down, and in other steps
- Know where the loop variable exists
Transcript
Everything said in the video, section by section (1,315 words). Read along, or search it.
Opening Problem
Three Things Every Counted Repetition Needs
Every repetition that runs a known number of times needs the same three things. Somewhere to start. A rule for when to continue. And a way to move from one round to the next. Print the numbers 1 to 5 by hand, and it's tedious but manageable. Make it 1 to 1,000, and it stops being an approach at all. Scattered across a program, those three are easy to get wrong. The for loop's one real contribution is to gather all three onto a single line, where you can verify them at a glance.
Syntax Anatomy
Initialization, Condition, and Update Sections
Here's a for loop that prints 1 to 5. Inside the parentheses are three sections, separated by two semicolons. The first, int i equals 1, is the initialization. It creates the counter and gives it its starting value. It runs once, before anything else. The second, i less than or equal to 5, is the condition. While it's true, the loop continues. It's checked before every round. The third, plus plus i, is the update. It moves the counter on, and it runs after every round. There are always exactly two semicolons, even when a section is left empty. And there's no semicolon after the closing parenthesis.
Execution Order
How the Three Sections Actually Run
The three sections don't run in the order they're written, and that's the source of most confusion about loops. Initialization runs once: i becomes 1. Then the condition is tested. 1 is at most 5, so it's true. The body runs one round of work, printing the 1. Then the update moves the counter on, to 2, and the condition is tested again. Round two prints 2. And so on, until i reaches 6. The condition is false, and the program carries on after the loop. Two consequences follow. The condition is tested first, so a loop can run its body zero times. And the update runs after the body, so the counter holds this round's value throughout it.
Quick Check
Counting Condition Tests in Five Rounds
Quick check. For a loop that carries out five rounds, how many times is the condition tested? Pause, and think.
Answer
Six Tests, Five Rounds
Six. Once before each of the five rounds, plus a final check that comes out false, and ends the loop. Initialization runs once. The body runs five times, and so does the update, once after each round, including the last. That's why the counter ends up just past the final value.
Edge Case
A Loop That Runs Zero Times
An empty repetition isn't an error. This loop starts at 0 while i is less than 0, so it never runs. And that's fine. A loop written to process five items will correctly do nothing at all when there are no items.
Variations
Counting Down, By Twos, or Doubling
Nothing in the three sections requires counting upward by one. Start at 1, continue while i is at most 5, and add 1: 1 to 5. Start at 5, continue while i is at least 1, and subtract 1: 5 down to 1. Start at 0, continue up to 10, and add 2 each time. Or start at 1, continue up to 64, and multiply by 2: it doubles. The initialization can start anywhere, the condition can point either way, and the update can move by any amount, as long as the three agree. Whatever the update does, it must move the counter toward a value that fails the condition. That sentence is the whole safety requirement.
Common Mistake
Unsigned Countdown Never Ends
Here's a countdown that looks entirely reasonable, and never ends. Unsigned int i equals 5, while i is at least 0, minus minus i. An unsigned value has no negative region. When i holds 0 and the update subtracts 1, it wraps around to the largest value the type can hold. So the condition, i at least 0, is true for every value an unsigned counter can ever hold. Count down with a signed type, or restructure the condition so that zero isn't the boundary.
Scope
Counter Belongs to the Loop
A counter declared in the initialization section belongs to the loop. It comes into existence when the loop starts, and is gone when the loop finishes. Try to print i on the line after the loop, and the compiler refuses. That's a feature, not a restriction. The same name is free for the next loop, with no chance of one interfering with another. And a value that only meant something during the repetition can't be read afterwards by mistake.
Alternative Form
Declaring the Counter Before the Loop
Compare a second placement. Declared before the loop, i exists throughout, and once the loop finishes it still holds 3. Declare the counter inside the loop unless you genuinely need its final value afterwards. That's the only reason to prefer this form. Notice it leaves the initialization section empty. That's entirely legal, but the semicolon stays.
Advanced Forms
Multiple Counters and Empty Sections
Each of the three sections may contain more than one item. A loop that works inward from both ends of a range uses two counters. The counter i starts from 0, and j from 10, continuing while i is less than j. Each round, i goes up and j goes down. Both are declared in one initialization, and advanced by one update, separated by commas. The condition still produces one bool. Leave all three sections empty, and you get for, semicolon, semicolon: an intentional forever-loop, whose exit must come from inside the body.
Common Mistake
The Stray Semicolon Empties the Body
An extra semicolon right after the closing parenthesis is legal, silent, and almost never what was meant. That semicolon is the loop's body: an empty statement. So the loop faithfully performs five rounds of doing nothing. The indented line below it isn't part of the loop at all, and runs once, afterwards. The indentation makes it look guarded, when it isn't. Clang warns about exactly this when asked. One habit prevents the whole family of faults: brace every body, even a single statement.
Choosing a Loop
When a Counted Loop Fits
The for loop suits repetitions where the number of rounds is settled before the repetition begins. The count needn't be a literal, but it must be known when the loop starts. If the task is, do this a set number of times, reach for a counted loop. If it's, keep going until something happens, reach for a condition-driven loop. Two of the three sections would sit empty. And for once for every item in a collection, a dedicated form, coming in lesson 6.2, removes the counter and its off-by-one risks.
Checklist
Five Faults to Check Before Running
Before you run a loop, check for five faults. Off by one at the boundary: less than 5 and less than or equal to 5 differ by exactly one round, so choose deliberately. An update that never fails the condition. The loop never ends, and nothing reports it. Counting down with an unsigned counter, which wraps at zero. And a semicolon after the parentheses, which empties the body. Finally, changing the counter inside the body. The loop still works, but its one-line summary is now a lie. Let the update own the counter.
Key Terms
Loop Vocabulary at a Glance
A few key terms. Iteration means carrying out the same statements repeatedly. One pass is one iteration, or round. A counter-based loop is controlled by a counter with a start, a continuing condition, and an update. The loop variable is that counter. Scope is the region of a program in which a declared name can be used. The step size is how far the update moves the counter each round. And an infinite loop is one whose condition never becomes false.
Key Takeaways
Summary and Closing Thought Question
To summarize. A for loop states where a count begins, how long it continues, and how it advances, all in one place. It runs the initialization once, tests the condition before every round, and applies the update after every round. So a loop can correctly run zero times. A counter declared in the loop vanishes when it ends. Brace every body, and count down with a signed type. Here's something to think about. In a loop from 1 to 5, what does i hold during the third round? And if i had been declared before the loop, what would it hold once the loop finishes?
About C++ Programming at UPI Study
C++ Programming (Computer Science 242) is a self-paced online course of 84 video lessons in 11 chapters, from your first program to decisions, loops, arrays, functions, classes, files, pointers and inheritance. 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 Every course with PRO →
Why take it here
Why students take C++ Programming with UPI Study
Where the credit goes
Universities that work with NCCRS
C++ Programming 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 Counter-Based Iteration
What are the three sections of a for loop in C++ and what does each one do?
In what order do the parts of a for loop run, and how many times is the condition checked?
How do I make a for loop count down or count by twos in C++?
Can I use the loop variable i after a for loop ends in C++?
About the C++ Programming course
How many college credits is C++ Programming?
How much does C++ Programming cost and what is included?
Which universities accept UPI Study credits?
How long does C++ Programming take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in C++ Programming.
84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →