UPI Study › Courses › C++ Programming › Free lessons › Lesson 5.8 Free with a free account
Real-World Repetition Scenarios
C++ Programming · Chapter 5: IterationSection 5.8 · lesson 36 of 84video coming soon
← Avoiding Loop Traps and DebuggingNext lesson: Arrays and Vectors Introduced →
In this lesson
Applying loop structures to practical tasks.
- Name which of 7 loop shapes a problem needs
- Make accumulators safe when there's no data
- Peel digits, generate sequences, test primes
- Read to a stopping value; print shapes and tables
Transcript
Everything said in the video, section by section (1,707 words). Read along, or search it.
Overview
Seven Shapes Behind Every Loop
Nothing new is introduced here. Everything ahead uses the three loop forms and the operators you already have. The work is recognizing which of a small number of repeating shapes a problem calls for, and getting the details right at the edges. Loop problems look varied, and aren't. Nearly all of them are one of seven shapes. An accumulator builds one value. A tracker remembers the best so far. A counter counts items meeting a test. A peeler takes a number apart by digits. A generator produces the next term from previous ones. A sentinel reader reads to a stopping value. And a nested printer makes rows and columns. Learning to name the shape before writing anything is most of the skill.
Core Pattern
Before, During, and After the Loop
Every accumulator and tracker has the same three regions. Before the loop, create the holders, and give each one a starting value. During the loop, for each item, update the holders, one item at a time. After the loop, use the holders, and first handle the case where there were none. Most faults live in the first and third regions, not the middle. And one question catches most of them: what should this hold if the loop never runs?
Scenario One
Total and Mean With an Empty Guard
Scenario one: the total and mean of n readings. Before the loop, total starts at zero, because a sum starts at zero. During the loop, each reading is read and added to the total. After the loop, the empty case comes first. If n is greater than zero, report the total and the average. Otherwise, report that no readings were entered. That guard is the whole point. Dividing by n without checking it is the single most common fault in this shape. Here the total is a double, so it would print nan, short for not a number. With whole numbers, it's undefined behavior: some machines stop the program, and others quietly print a wrong answer.
Scenario Two
Tracking Highest and Lowest Readings
Scenario two: the highest and lowest of n readings. The first value is read on its own, and both lowest and highest are seeded with it. Then the remaining readings are read in the loop, updating whichever tracker they beat. Trace it with minus 4, minus 9, and minus 2. Both trackers are seeded at minus 4. Minus 9 is lower, so lowest changes. Minus 2 is higher than minus 4, so highest changes. At the end, lowest is minus 9 and highest is minus 2. Both are values that were actually entered.
Design Reason
Why Trackers Start With the First Value
Why seed the tracker with the first value? Starting highest at zero seems harmless, and it's wrong for any data set where every value is negative. The reported maximum is zero: a number nobody entered. Starting lowest at zero fails the same way when every value is positive. Seeding with the first actual reading is correct for every data set. And it makes the no-data case obvious, because there's no first reading to seed with.
Scenario Three
Counting Multiples of 3 Not 5
Scenario three: how many values from 1 to n are divisible by 3, but not by 5? A counter is an accumulator that adds one instead of a value, and only when a test holds. Here, the test is i mod 3 equals 0, and i mod 5 isn't 0. With n equal to 20, the matches are 3, 6, 9, 12, and 18. Fifteen is excluded, so the count is 5. The condition is the whole problem. The loop is scaffolding.
Technique
Peeling Digits With Remainder and Division
Two operations take a number apart. The remainder after dividing by 10 gives the last digit. Whole-number division by 10 removes it. Repeating the pair peels the number from the right until nothing is left. And the answer is built by multiplying by 10 and adding each digit. Peel 4071. The remainder gives 1, and 407 is left. Reversed becomes 1. Then 7, leaving 40: reversed is 17. Then 0, leaving 4: reversed is 170. Then 4, leaving nothing: reversed is 1704.
Scenario Four
Reversing a Number and Its Edges
Scenario four is this reversal. Work on a copy, because the loop destroys it. Reversed starts at zero. The shape always has two edges. Entering 0 produces no passes at all, so the answer stays 0. That happens to be right, but only by luck. And a number ending in zero loses it. 4070 reverses to 704, because a leading zero can't exist in a number. Both are behaviors to know about, and state in your specification. The same peeling shape answers other questions with one line changed: add each digit to a sum to total the digits, or add one to a count to count them.
Quick Check
Predicting the Reversal of 1050
Pause and predict. What does the reversal loop print when you enter 1050? Five hundred one. The digits peel off as zero, five, zero, one. The first zero adds nothing, but the middle one is kept.
Scenario Five
Factorial as a Product Accumulator
Scenario five: factorial, as a product accumulator. Result starts at 1, not 0. For i from 2 up to n, multiply result by i. For n equal to 0 or 1, there are no passes, so the result stays 1, which is correct. Starting a product at zero would give zero for every input. That's the arithmetic version of the question, what should this hold if the loop never runs? And this shape runs out of room quickly. 20 factorial still fits. 21 factorial exceeds even the largest whole-number type here, and the answer silently becomes wrong.
Scenario Six
Prime Test Stopping at the Square Root
Scenario six: is n prime? The flag starts as n greater than 1, because 1 and below aren't prime. Then d runs from 2, while d times d is at most n. If n is divisible by d, it isn't prime, and the loop breaks. The condition stops at the square root without ever computing one. Any divisor above the square root pairs with one below it, which would already have been found. And leaving early isn't just an optimization. It's a statement of meaning: once a divisor exists, nothing further can change the answer. Try 36. Then 37, which has no divisor up to its square root. And 1, which the flag rules out at the start.
Scenario Seven
Fibonacci and the Saved Temporary
Scenario seven: the first n Fibonacci terms. A starts at 0, and b at 1. Each pass prints a, computes next as a plus b, then moves a to b, and b to next. Pass one prints 0, and next is 1. Pass two prints 1, and next is 2. Pass three prints 1, and next is 3. Pass four prints 2, next is 5. Pass five prints 3, and next is 8. The line that saves next exists because the following line destroys the value, that the line after it needs. Remove that temporary, and write a equals b, then b equals a plus b. The same five terms now come out as 0, 1, 2, 4, 8. That's doubling, not Fibonacci. By the time b is computed, a no longer holds the value it was supposed to contribute. Any generator that carries more than one value forward needs this care.
Scenario Eight
Sentinel Input With a Priming Read
Scenario eight: when the quantity of data is unknown, agree on a value that ends the input. It must be one that could never be genuine data. Here, a priming read comes first. Then, while the value isn't minus 1, add it to the total, count it, and read the next. The two reads look like duplication, and aren't. The first supplies a value for the test. The one at the end of the body supplies the next. Read only inside the body, and the loop tests a value it hasn't been given. Read only before it, and the loop never advances. And the stopping value is never added and never counted, because the test happens before the body runs.
Scenario Nine
Pyramid Rows, Spaces, and Stars
Scenario nine: when output has rows and columns, the outer loop counts rows, and the inner one counts positions within a row. This centered pyramid uses two inner loops per row: one prints spaces, the other prints stars. Then the outer loop ends the line. The two counts are the design. At row r of n, there are n minus r spaces, and 2 r minus 1 stars. So when n is 4, row 1 has 3 spaces and 1 star. Work those counts out on paper before writing the loops. A wrong shape is almost always an arithmetic error in those two expressions, rather than a loop error.
Debugging
Symptoms of a Misbehaving Loop
When a loop misbehaves, check these before reading the whole body again. One item too many or too few means the wrong comparison. A nonsense total means an accumulator never given a starting value. A total that's always the last value means total equals x, where total plus x was meant. A maximum of zero for negative data means a tracker seeded with zero. A loop that runs forever has nothing in the body changing the tested value. If the stopping value lands in the total, the test happens after the body. And if an average fails, nothing was counted. Guard before dividing.
Practice Set
Assignments and Evidence to Submit
Now the practice set. For each task, hand in the program, name the shape, and show its results on the check values, plus an edge case of your own. One: summarize seven temperatures. With 3, minus 2, 0, 8, minus 5, 4, and 1, the average is 1.3. It must also work if all seven are negative. Two: the digit count, digit sum and reverse of 4071. Three: count divisors, then test for a prime. Four: read prices until minus 1, and report no items, rather than dividing by zero. Five: Fibonacci terms up to a limit, not a fixed count. Submit with evidence: name the shape, run the check values, and add an edge case of your own, with its result worked out by hand.
Key Takeaways
Name the Shape, Guard the Edges
To summarize. Seven shapes cover nearly every loop problem, so name the shape before you write anything. Ask what each holder should contain if the loop never runs. Seed trackers with real data, and guard every average against an empty count. In a generator, save values before overwriting them. And when reading to a stopping value, test before the body. Here's something to think about. In the pyramid with four rows, how many spaces and stars does row 3 have? Check against n minus r, and 2 r minus 1.
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 Real-World Repetition Scenarios
How do I know which kind of loop problem I'm solving in C++?
Why should a max or min tracker start with the first value instead of 0?
How do you reverse a number digit by digit with a loop in C++?
How does a sentinel-controlled loop with a priming read work?
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 →