UPI Study › Courses › C++ Programming › Free lessons › Lesson 5.2 Free with a free account
Dissecting the for Loop
C++ Programming · Chapter 5: IterationSection 5.2 · lesson 30 of 84video coming soon
← Counter-Based IterationNext lesson: The while Loop Mechanism →
In this lesson
Step-by-step execution and output tracing.
- State the exact order the four parts run in
- Build and fill in a desk-check trace table
- Count the repetitions without running anything
- Read a trace to find an off-by-one fault
Transcript
Everything said in the video, section by section (1,288 words). Read along, or search it.
Opening Idea
Written Order Versus Running Order
A loop is four small pieces that run in a fixed order. Almost every fault beginners meet with loops comes from a wrong belief about that order. The header of a counting loop holds three separate pieces of code, and the body is the fourth. First, the initialization runs once, before anything else, and never again. Second, the condition is tested before every pass, including the first, and once more at the end. Third, the body runs only on a pass where the condition came back true. And fourth, the update runs after the body has finished, never before it. On the page, they're written in the order one, two, four, three. The order they're written in isn't the order they run in.
Execution Sequence
Test, Body, Update Until Failure
Written as a sequence, one full run goes like this. Initialize once. Then test, body, update. Test, body, update. And so on. Until a test comes back false. At that point, the loop stops immediately. The body doesn't run, and the update doesn't run either. After every update, it's back to the test, never straight to the body. That explains a fact that confuses many people. The loop finishes because a test failed, and that test was made on a value the update had just produced. So when i less than or equal to 5 finally stops a loop, i holds 6, not 5.
Worked Example
Trace Table for Summing One to Five
A trace table is the loop written out one step at a time, by hand, with a column for every value that changes. Here, total starts at 0, and the loop adds each value of i from 1 to 5, printing i and the running total. Give the table one row per test, not per line of code. Each row records the counter at the test, whether it passed, what the body did, and what the update left behind. Pass one: i is 1, the test is true, the total becomes 1, it prints 1 and 1, and the update leaves i at 2. Pass two: the total becomes 3, and i becomes 3. Pass three: 6. Pass four: 10. Pass five: 15, and the update leaves i at 6. The final row: i is 6, the test is false, the body is skipped, and the update is skipped too. Now read straight off the table: the body ran 5 times, the output has 5 lines, and i is 6 when the loop is over. The last row, where the test fails, is the one people leave out. It's also the row that answers most of the questions they then have.
Shortcut
Counting Passes Without Tracing
Tracing every pass is the right tool for understanding a loop, and the wrong tool for a loop that runs 200 times. The count follows from three numbers: where the counter starts, what it's compared against, and how much the update changes it. From a up to b inclusive, stepping by one, the count is b minus a plus one. So 1 to 5 gives 5. With a strict less-than, it's just b minus a. Zero up to 5, exclusive, also gives 5. With a step, divide the distance by the step. Zero to 10 by threes: three, rounded down, plus one, gives 4 passes. Counting down from a to b inclusive gives a minus b plus one: 10 down to 7 is 4 passes. In every case, if the condition is already false at the start, the answer is zero, and no formula is needed.
Analogy
Fenceposts and the Plus One
The plus one in the inclusive forms is the whole subject in miniature, and it has a name: the fencepost. Take a fence 40 meters long, with a post every 10 meters. Four posts... no: look at the drawing, five posts. There are 4 gaps, and 5 posts. Subtracting the bounds counts the gaps, and the loop runs once per post. Both loops here cover the same span. From 1, while i is at most 5, makes 5 passes. While i is less than 5, it makes 4, and 5 is never reached. So choosing between less-than and less-than-or-equal isn't taste. It changes the repetitions by exactly one.
Quick Check
Predicting Three Loop Outputs
Now predict some output, before looking at the answers. One, two, three. Pause, and work each one on paper. One: ten, nine, eight, seven. That's four passes, by 10 minus 7 plus 1. The counter ends at 6, and nothing is printed for it. Two: one, four. Two passes, by 3 minus 1. It prints the square, not the counter, and 9 is never printed. Three: done, and nothing else. The condition is false at the very first test. Zero passes is a normal, correct outcome. A program that prints nothing where you expected output is often exactly this.
Common Mistake
Recognizing Off-By-One Faults
An off-by-one fault is a loop that repeats one time too many, or one too few. It rarely announces itself. The program runs, produces plausible output, and is wrong at exactly one end. A trace finds it in under a minute. One extra pass at the end means the body ran on the bound itself: less-than-or-equal where less-than was meant. One missing at the end is the reverse. One missing at the start points at the initialization. Twice as many passes, or half, points at the update. And if it never stops, the counter is identical in every row. The update is missing, or changes something other than the value the condition tests.
Case Study
The Even Numbers Bug Report
A worked diagnosis. The intention is to print the first 5 even numbers. The loop starts at 2, continues while i is at most 10, and adds 2 each time. The report says it prints one number too many. Trace the two ends, rather than the middle. Pass one: i is 2, true, it prints 2, and the update leaves 4. Pass five: i is 10, true, it prints 10, and the update leaves 12. Then 12 fails the test. So the trace says five passes: 2, 4, 6, 8, 10. That's exactly what was asked for. The loop is correct, and the report is wrong. The person expected the first five even numbers to begin at zero.
Technique
Tracing Only the Two Ends
For a loop of any length, write the first two rows, a row of dots, and the last two rows. The first rows show whether the counter starts in the right place and moves by the right amount. The last rows show whether the loop stops one value too early, or too late. Off-by-one faults live at the boundaries. Thirty identical middle rows cost twenty minutes and reveal nothing. If the two ends are right and the step is right, the middle follows. And a trace settles arguments in both directions. Half the time, it shows the loop is wrong. The other half, it shows the requirement was never agreed.
Key Terms
Pass, Trace Table, Desk Check
A few key terms. A pass is one complete execution of the body, with the test that permitted it and the update that followed. A trace table is a hand-written record of every value at every step, one row per test. A desk check means working code by hand, on paper, without running it. An off-by-one fault makes a loop repeat one time too many or too few. And the fencepost is the counting relationship behind it: five posts have four gaps.
Think About It
Counting By Fours Up to Twenty
Here's something to think about. Starting at 4, while i is less than 20, adding 4 each time: how many passes? And which values does the counter take? Pause, and trace it. Four passes: the values are 4, 8, 12 and 16, and the count is 20 minus 4, over 4. Twenty fails the test, so it never runs the body. To summarize: initialize once, then test, body, update, and stop the moment a test fails. Trace the two ends to find an off-by-one.
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 Dissecting the for Loop
In what order do the four parts of a for loop run in C++?
How do I build a desk-check trace table for a for loop?
How can I count how many times a for loop repeats without running it?
How do I use a trace to find an off-by-one error in a for loop?
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 →