Real-World Repetition Scenarios, Explained with Code Examples

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 →

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

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.

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 Real-World Repetition Scenarios

How do I know which kind of loop problem I'm solving in C++?
Nearly every loop problem fits one of seven shapes. An accumulator builds one value. A tracker remembers the best so far. A counter counts items that pass a test. A peeler takes a number apart by digits. A generator produces the next term from earlier ones. A sentinel reader reads to a stopping value. A nested printer makes rows and columns. Name the shape before writing code.
Why should a max or min tracker start with the first value instead of 0?
Seeding with the first reading is correct for every data set, while starting at 0 is not. If highest starts at 0 and the readings are -4, -9, -2, the program reports 0, a number nobody entered. Starting lowest at 0 fails the same way when every value is positive. Read the first value, set both trackers to it, then loop through the rest.
How do you reverse a number digit by digit with a loop in C++?
Peel digits with remainder and division: while the working copy is not 0, take digit = n % 10, set reversed = reversed * 10 + digit, then n = n / 10. Start reversed at 0 and work on a copy, because the loop destroys the number. For 4071 this produces 1704. A number ending in zero loses it: 4070 reverses to 704.
How does a sentinel-controlled loop with a priming read work?
A sentinel loop reads one value before the loop, tests it, and reads the next value at the end of the body. For example: cin >> x; while (x != -1) { total += x; count++; cin >> x; } The test runs before the body, so the stopping value is never added or counted. If count is 0 afterward, report no items instead of dividing.

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 →