Website by Joshua Bleier

Module 2.2 - For Loops & Nested Loops

Extending on the for loop
Take another look at factorial.c, and recall that we're calculating it as

1 * 2 * 3 * ... * n.

Can you rewrite this program so that it makes the calculation as

n * (n - 1) * (n - 2) * ... * 1

instead?

Applied Nested Loops
Next, let's look at the application of nested loops to real world situations: bisect.c employs the bisection method (An ideal candidate for a do loop, because the bisecting function should be run at least once), and it's sister program, bisect_fxn.c, does the same thing, but makes use of the concept of user-defined functions. We'll cover user-defined functions in a subsequent module, but briefly, they allow you to:

  • organize the computations of a program into modular, more easily-understood chunks.
  • handle computation that must be performed numerous times over different sets of data.

Also, spend some time going over integ_complete.c (And the equivalent employing a user-defined function, integ_complete_fxn.c) which uses nested loops to implement integration for finding the area under a curve.

Finally, mol.c loops over potential molecules to determine which ones would fit  with a user-input molecular weight.

The mol.c program nests multiple for loops to make it's calculations; can you modify the program so that it uses only do loops? while loops? Which do you think is most appropriate for this problem? Why?

Can you come up with a real-world example of your own that would use a loop? How about nested loops?

Finally, take a look at the About.com tutorial on loops, as well as the HowStuffWorks tutorial; both cover all three C looping structures, but the HowStuffWorks looping example includes an insert that points out some very common programming errors to avoid, and eliminates the painfully ubiquitous pop-up and animated ads prevalent throughout About.com.

Continue to the Files Module ->