Nested Loops and Common Loop Errors | Programming in C

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

← Interrupting Normal Flow: break, continue, and gotoNext lesson: Workshop: Summation, Factorial, and Input Validation →

Earn 3 college credits for Programming in CRecommended for credit by NCCRS · Computer Science 240 · self-paced · one payment, lifetime access

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.

Compare: C vs C++

Why take it here

Why students take Programming in C with UPI Study

How programs work close to the machineProgramming in C teaches how a program uses memory: variables and data types, control flow, functions, arrays and strings, pointers, files, structures and dynamic memory. C is the base for operating systems, embedded devices and many computer-science courses.
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

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.

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?
When the inner loop makes the same number of passes every time, the inner body runs outer passes times inner passes, so three rows of four columns run it 12 times. If the inner limit changes with the outer counter, add the passes instead. With r from 0 to 3 and c from 0 up to and including r, the counts are 1 + 2 + 3 + 4 = 10.
How do you print a pyramid of stars with nested loops in C?
For each row, print the spaces first and then the stars, using two inner loops one after the other. In a four-row pyramid, row r gets 4 - r spaces and 2 * r - 1 stars, so the rows have 1, 3, 5 and 7 stars. Writing the star limit as row * 2 instead of row * 2 - 1 puts one extra star on every row.
Why does a semicolon after a for statement cause a bug?
A semicolon right after the for header's closing parenthesis becomes the loop's entire body, since a lone semicolon is an empty statement. The line meant to repeat then runs only once, after the loop finishes. With -Wall, clang warns that the for loop has an empty body and suggests putting the semicolon on its own line if that was intended. The program still builds.
What happens if a nested loop uses the wrong loop variable?
The program usually compiles without a warning and prints wrong output. Writing row * row instead of row * col in a times table makes each line repeat one number, because col is never used. Sharing one counter between the outer and inner loops is a related bug, since the inner loop changes the outer loop's count. Distinct, clear names such as row and col make the slip easier to spot.

About the Programming in C course

How many college credits is Programming in C?
Programming in C (Computer Science 240) 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 Programming in C cost and what is included?
$250, paid once, with lifetime access: all 78 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 Programming in C take?
It is self-paced with no deadlines. The 78 lessons total about 9 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 Programming in C.

78 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Programming in C
3 credits · NCCRS
Enroll →