UPI Study › Courses › Programming in C › Free lessons › Lesson 5.6 Free with a free account
Nested Loops and Common Loop Errors
Programming in C · Chapter 5: Loop Constructs, Control Statements, and Error DiagnosisSection 5.6 · lesson 31 of 787 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Programming in C.
Lesson complete
Earn the 3 college credits for Programming in C
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Workshop: Summation, Factorial, and Input Validation →← Interrupting Normal Flow: break, continue, and gotoNext lesson: Workshop: Summation, Factorial, and Input Validation →
In this lesson
Loops inside loops for grids and patterns, plus four classic bugs.
- Calculate how many times a nested loop's inner body runs
- Build star patterns by working out each row's character counts
- Identify off-by-one, wrong-variable, stray-semicolon and infinite-loop errors
- Explain why the inner and outer loops need separate counters
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,069 words). Read along, or search it.
Opening Analogy
A Clock's Two Hands
Look at a clock. The minute hand goes all the way around, while the hour hand moves one step. Then the hour hand moves again, and the minute hand goes all the way around again. That's a loop inside a loop. With it, a program can walk across a grid, print a times table, or draw a picture out of stars. It also brings new ways to go wrong. So this lesson ends with the mistakes every C programmer makes, sooner or later.
Nested Loops
Three Rows of Four Bins
A nested loop is a loop placed inside the body of another loop. The Starlight Arcade has token bins in three rows of four, numbered row by row. The outer loop picks a row. For each row, the inner loop runs completely, from its start to its end, before the outer loop moves on. Row one: column one, two, three, four. Only then does row become two, and the column starts again at one. Like the minute hand, the inner loop moves fastest. Build and run it. Three rows of four numbers, and the inner body ran twelve times. That's the rule to remember: passes of the outer loop, times passes of the inner loop. Three times four is twelve. The newline printf sits in the outer body, after the inner loop, so it ends each row once. Inside the inner loop, every number would land on its own line.
Worked Example
A Five by Five Times Table
A times table uses the same shape. The row number is printed first, as a label, and each cell is row times column. Build and run it. Five rows of five cells. Check one cell by hand: row four, column three. Four times three is twelve, and there it is. One mistake to avoid: running the outer and inner loops on the same variable, declared before both. Then the inner loop changes the outer loop's counter, and the passes no longer add up to rows times columns. Always use two different counters.
Patterns
A Triangle of Stars
Patterns are a favorite way to practice nested loops, and the trick is always the same: for each row, how many of each character? A triangle has one star in row one, two in row two, and so on. So the inner loop runs up to row, not up to a fixed number. Build and run it: one, two, three, four stars.
Patterns
Spaces Then an Odd Number of Stars
A pyramid needs spaces first, and then an odd number of stars. So it uses two inner loops, one after the other. Row r gets four minus r spaces, and then two times r, minus one, stars. Row one is three spaces and one star. Build and run it: one, three, five, seven stars. Priya, who writes the arcade's programs, once wrote the second test as s at most row times two. Sam, who tests the programs, checked her run against the counts one, three, five, seven. Row one had two stars. Every row had one star too many. The limit should have been row times two, minus one.
Quick Check
A Shrinking Triangle
Quick check. Same outer loop, but now the inner loop runs s from one, up to five minus row. How many stars does each line get? Pause and predict. A shrinking triangle: four stars, then three, two, and one. Row one gives five minus one, four stars. Row four gives five minus four, just one. The count goes down as row goes up. Five stars would need the limit to be six minus row. Always check the first row and the last row by hand.
Common Errors
Four Classic Loop Mistakes
Now the mistakes. Four of them catch almost everyone. An off-by-one. The wrong loop variable. A stray semicolon. And a loop that never ends. Each one has a fix.
Error One
One Pass Too Few
First, off by one: one pass too many, or one too few. Priya counts five machines, numbered one to five. With less than five, the loop stops before five, so the fifth machine is never visited. With less than or equal to five, all five are. Run it: four passes, then five. No warning either way.
Error Two
Typing Row Where Col Belongs
Second, the wrong loop variable. With two loops, it's easy to type row where you meant col. Here's the times table again, with row times row in each cell. It still compiles, without a warning. Build and run it. Every line repeats one number, because col is never used. The only clue is a wrong answer, so compare it with a cell you worked by hand. Clear names, like row and col, make this slip easier to spot.
Error Three
A Semicolon After the for Header
Third, a semicolon after the for header. A lone semicolon is a complete statement that does nothing. Put one right after the closing parenthesis, and it becomes the loop's whole body. The line you meant to repeat runs once, after the loop is done. With dash W all, clang notices: for loop has empty body. It even suggests putting the semicolon on its own line, if an empty body is what you really meant. It still builds, so run it: ten tokens, not thirty. Read your warnings. This one is a real bug.
Error Four
A Loop With No Update
Fourth, a loop that never ends. An infinite loop never makes its condition false. The usual cause is a missing update, like n here. Build and run it, and the same line prints again and again. N never changes, so n at most three stays true. On a terminal, Control C interrupts it. Never run a loop like this without a way to stop it. An update that moves the wrong way, away from the end, is just as bad.
Quick Check
An Inner Limit That Grows
Quick check. The outer loop runs r from zero to three. The inner loop runs c from zero up to r, and counts every pass. What is count at the end? Pause and predict. It prints count equals ten. The inner loop's limit grows with r: one pass when r is zero, then two, three, and four. One plus two plus three plus four is ten. Sixteen is the rows-times-columns rule, which only holds when the inner loop makes the same number of passes every time.
Key Takeaways
Nested Loops and Errors in Review
To sum up. In a nested loop, the inner loop runs completely for every pass of the outer loop. Its body runs outer passes times inner passes, when the inner count is fixed. For patterns, work out how many of each character every row needs. And watch for the four classics: off by one, the wrong variable, a stray semicolon, and a loop that never ends.
About Programming in C at UPI Study
Programming in C (Computer Science 240) is a self-paced online course of 78 video lessons in 11 chapters, from pseudocode and your first program to data types, decisions, loops, functions, arrays, strings, pointers, files, structures, dynamic memory and linked lists. 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 All Computer Science courses Every course with PRO →
Compare: C vs C++
Why take it here
Why students take Programming in C with UPI Study
Where the credit goes
Universities that work with NCCRS
Programming in C 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 Nested Loops and Common Loop Errors
How many times does the inner body of a nested loop run?
How do you print a pyramid of stars with nested loops in C?
Why does a semicolon after a for statement cause a bug?
What happens if a nested loop uses the wrong loop variable?
About the Programming in C course
How many college credits is Programming in C?
How much does Programming in C cost and what is included?
Which universities accept UPI Study credits?
How long does Programming in C take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Programming in C.
78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →