The Rationale Behind Loops, Explained with Code Examples

UPI Study › Courses › C++ Programming › Free lessons › Lesson 4.8 Free with a free account

The Rationale Behind Loops

C++ Programming · Chapter 4: Decision MakingSection 4.8 · lesson 28 of 84video coming soon

← Real-World Decision ScenariosNext lesson: Counter-Based Iteration →

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

In this lesson

When code needs to repeat.

  • Spot repetition in an ordinary-language requirement
  • Explain why copying the work out fails
  • Answer the three questions every loop must answer
  • Choose between counter, sentinel and condition loops

Transcript

Everything said in the video, section by section (1,692 words). Read along, or search it.

Opening Idea

Same Work, Done Again

A great deal of what a program does is the same work, done again. Not similar work, but the same work, on a different item, or at a different moment. Describing that work once, and saying how many times it should happen, is what a loop is for. Deciding what to say is a design question that has nothing to do with any particular language. So there's no C plus plus in this lesson at all. Every loop is written in pseudocode. The syntax comes next, and it's much easier to learn once you know what you're trying to say.

Spotting Repetition

Signal Words That Hint at Loops

Repetition rarely announces itself as a loop. It arrives in ordinary phrasing, and a handful of words are reliable signals. For each item, or all the records: the work done to one item repeats, and what changes is which item you're on. Until the user is finished: one round of work repeats, and new input arrives each pass. The total, or how many: the repeated work is adding one contribution to a running result. Keep trying, or one at a time: the attempt repeats. And the largest, or check whether any: one candidate is compared against the best so far. The third and fifth are the ones people miss. Total and largest never mention repetition at all, yet there's no way to get either without visiting every item.

Try It

Four Repetitions in One Sales Report

Try it on this requirement. The operator enters each sale as it happens. At the end of the day, the system reports how many sales were made, the total value, and the largest single sale. That one requirement implies four separate repetitions. Entering sales one at a time. Counting them. Totaling them. And tracking the largest. All four visit the same items, so in practice they become one loop that maintains four pieces of information at once.

Alternative

Why Copying Out the Work Fails

The obvious alternative to a loop is to write the work out as many times as needed. For exactly five items, it even looks reasonable. It fails for four reasons, and only the first is about effort. The count is often unknown. You can't write a block once per sale when nobody knows how many sales today will bring. The count changes. Code written for five items is wrong the moment there are six. Every fix must be made many times. Miss one copy, and the program is inconsistent, for some inputs only. And intent disappears. Dozens of near-identical lines don't say, do this for every item.

Comparison

Five Temperatures Described Once

Described once, it's: set total to zero, then repeat five times: read a temperature, and add it to the total. The looped version is shorter, but that's the least of it. It states the intention outright, and it's corrected in one place. Changing five to five hundred is a single edit, in one place. The duplicated version becomes impossible the moment the number of readings isn't known in advance.

Core Idea

Three Questions Every Loop Answers

Whatever form it eventually takes, a loop is a complete answer to three questions. Where does it start? When does it stop? And what changes each pass? Print the numbers 1 to 10. A counter starts at 1. The loop stops once it passes 10. And the counter rises by 1 each pass. Pass one prints 1, and the counter becomes 2. Pass two prints 2, and the counter becomes 3. After the tenth pass, the counter is 11, the test fails, and the loop stops.

Applying It

The Same Answers Across Common Tasks

The same three answers fit every task. To total a list of prices: the total starts at 0 with the first item, it stops after the last item, and each pass brings a new item. To read entries until done: read the first entry, stop when the entry is done, and read a new entry each pass. And to ask until the answer is valid: nothing is accepted yet, it stops when a valid answer arrives, and each pass takes a fresh attempt.

Common Mistakes

How Each Question Goes Wrong

Each question has a characteristic failure attached to it. Start, answered wrongly: a total that begins at something other than zero is wrong by a fixed amount, every time. That's the kind of bug that looks like a mystery until someone checks the first line. Stop, answered at the wrong boundary: the loop runs one pass too many, or one too few. This is the off-by-one error. And nothing changes. If the body never moves the situation toward stopping, the condition stays true forever. Every infinite loop is this question left unanswered.

Loop Shapes

Counter, Sentinel, or Condition-Driven

Repetitions differ in what decides when to stop, and almost every loop falls into one of three shapes. Recognizing which one a problem calls for is the main design decision. Counter-controlled loops stop when a count reaches its limit. Use them when the number of passes is known before you begin. The danger is off-by-one at the boundary. Sentinel-controlled loops stop when a marker appears in the data, such as minus 1, or done. The marker must never be counted or totaled. Condition-driven loops stop when some situation stops holding: while data remains, or while the answer is invalid. Something in the body must be able to change that situation. One question separates them. At the moment the loop begins, could you already say how many passes there'll be? If yes, counter. If not, ask what will tell you to stop.

Design Choice

Choosing a Safe Sentinel Marker

The sentinel shape deserves an extra word, because the choice of marker is a real design decision, not a formality. If sales are being entered and zero is the marker, a genuine sale of zero can never be recorded. If temperatures are entered, minus 1 is a plausible reading, and it would end the loop early. The marker has to be a value the real data can never take. Sometimes that means a word instead of a number, like close, which no sale amount could ever be.

Pseudocode

Two Reads in the Sentinel Loop

Pseudocode and flowcharts describe the same thing. Pseudocode is quicker to write, and easier to change. On the left, the counter-controlled version: set a counter to 1, then while it's at most 10, display it and add 1. On the right, the sentinel version: read an entry. Then, while the entry isn't done, process it and read another. Look closely. There are two read instructions. One comes before the loop, so the first entry exists to be tested. The other comes at the end of the body, so each pass brings in the next. Leaving out either is a classic fault.

Quick Check

Leaving Out the Second Read

Quick check. Suppose the second read, at the end of the body, is left out. What happens? Pause, and trace it.

Answer

The Same Entry Forever

The same entry is processed forever. Nothing in the body changes the entry, so the test can never fail. An infinite loop: the third question, left unanswered.

Flowcharts

A Decision With a Returning Path

A flowchart makes the path of execution visible, which is why it's the better tool when a loop misbehaves. Here's the sentinel loop. Total and count start at zero, and the first entry is read, so there's something to test. Then the decision: is the entry the marker? If yes, report and stop. If no, the body runs: count up by one, add the entry to the total, and read the next entry. A path leads back to the test. In flowchart form, a loop is simply a decision with a path that returns to it. Where that decision sits carries meaning. Test before the body, and a false condition means zero passes. Test after, and there's at least one pass. After is right for ask, then check the answer. It's wrong for process each item, when there might be no items at all.

Worked Design

Choosing the Shape for the Shop

Now a worked design. A shop needs the number of sales in a day, the total value, and the average sale. The operator types each sale, and enters the word close when the day is over. Is there repetition? Yes. Each sale, total and average all point at visiting every sale, and one loop can maintain everything needed. Which shape? The count isn't known when the day begins, so it's not counter-controlled. The operator signals the end with a specific value, so it's sentinel-controlled. Where does it start? Count at zero, total at zero, and the first entry already read. When does it stop? As soon as the entry is the word close. That entry is a signal, not a sale, so it's neither counted nor added. And each pass, the count rises by one, the sale is added, and the next entry is read.

Design Trace

Tracing Entries and the Empty Day

Here's the design in full. Set count and total to zero, and read an entry. Suppose the day's entries are 40, 25, and close. The first entry is 40, not close. Count becomes 1, total becomes 40, and the next entry is read: 25. Count becomes 2, total becomes 65, and the next entry is close. The test fails, and the loop ends. Now the case the requirement didn't mention: a day with no sales at all. The loop copes on its own. The first entry is the marker, so the body never runs. The average doesn't survive so easily. Dividing zero by zero has no answer. That's why the design ends with a test rather than a division.

Key Terms

Vocabulary of Loops

A few key terms. A pass, or iteration, is one complete run through the repeated work. Initialization is the setting-up before the first pass. The termination condition is the test that decides whether to continue. The update is the change each pass that moves the loop toward stopping. A sentinel is a value in the data that marks the end, and never one real data could take. And an infinite loop is one whose stopping condition never becomes true.

Key Takeaways

Summary and a Scores Puzzle

To summarize. Each, total and largest all imply a loop, even when repetition is never mentioned. Copying the work out fails when the count is unknown or changes. Every loop answers: where it starts, when it stops, and what changes. Pick the shape by asking whether the count is known when the loop begins. Here's something to think about. Scores run from 0 to 100, and minus 1 ends input. Is that a safe marker? If it were added in, how far off is the total?

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 The Rationale Behind Loops

How can I tell that a requirement needs a loop?
Look for wording that implies the same work happening more than once, such as "for each item," "until the user is finished," "keep trying," "the total," or "the largest." Total and largest never mention repetition, but neither can be produced without visiting every item. Each signal word points to work that repeats while something changes.
Why can't I just copy and paste the code instead of using a loop?
Copying the work out fails because the number of repeats is often unknown, and code written for five items is wrong once there are six. Every fix must also be made in every copy, and missing one makes the program inconsistent. Dozens of near-identical lines also hide the intent, which a loop states directly.
What three questions does every loop have to answer?
Every loop must say where it starts, when it stops, and what changes each pass. For printing 1 to 10: a counter starts at 1, the loop stops once the counter passes 10, and the counter rises by 1 each pass. If the third answer is missing, nothing moves the loop toward stopping, which produces an infinite loop.
How do I choose between a counter, sentinel, and condition-controlled loop?
Ask whether you can say how many passes there will be when the loop begins. If yes, use a counter loop. If not, ask what signals the end: a special marker value in the data means a sentinel loop, while a situation that stops holding, such as data remaining or an answer being invalid, means a condition-driven loop. A sentinel must be a value real data can never take.

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 →