Dissecting the for Loop, Explained with Code Examples

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 →

Earn 3 college credits for C++ ProgrammingRecommended for credit by NCCRS · Computer Science 242 · self-paced · one payment, lifetime access

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.

Why take it here

Why students take C++ Programming with UPI Study

Your first real programming languageC++ teaches how programs really work: variables, control flow, functions, memory and objects. It is the base for data structures, algorithms, systems and game programming, and for most computer-science degrees.
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

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.

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++?
The initialization runs once, then the condition is tested, then the body runs if the test was true, then the update runs, and control goes back to the test. The header is written as initialization, condition, update, with the body after it. The loop ends the moment a test fails, so for (int i = 1; i <= 5; i++) finishes with i equal to 6.
How do I build a desk-check trace table for a for loop?
Make one row per condition test, with a column for every value that changes. For total = 0 and for (int i = 1; i <= 5; i++) total += i; the first row is i = 1, test true, total becomes 1, update leaves i at 2. The last row is i = 6, test false, body and update skipped. Total ends at 15, and the body ran 5 times.
How can I count how many times a for loop repeats without running it?
Use the start value, the bound, and the step. Counting up by one, an inclusive bound gives b minus a plus one, and a strict less-than gives b minus a. With a larger step and a strict bound, divide the distance by the step and round up: for (int i = 0; i < 10; i += 3) runs 4 times (0, 3, 6, 9). If the condition is false at the start, the answer is zero.
How do I use a trace to find an off-by-one error in a for loop?
Trace only the first two and last two rows, because off-by-one faults sit at the boundaries. An extra pass at the end means the body ran on the bound itself, often <= where < was meant. A missing pass at the start points to the initialization. Doubled or halved passes point to the update. Check the requirement too, since the loop may be correct.

About the C++ Programming course

How many college credits is C++ Programming?
C++ Programming (Computer Science 242) 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 C++ Programming cost and what is included?
$250, paid once, with lifetime access: all 84 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 C++ Programming take?
It is self-paced with no deadlines. The 84 lessons total about 0 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 C++ Programming.

84 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

C++ Programming
3 credits · NCCRS
Enroll →