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 →
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.
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 The Rationale Behind Loops
How can I tell that a requirement needs a loop?
Why can't I just copy and paste the code instead of using a loop?
What three questions does every loop have to answer?
How do I choose between a counter, sentinel, and condition-controlled 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 →