San Diego State University logo
ME 203

Module 2.1 - Loop Basics

In this modules, we'll be making use of files in the tar file Decompress module2.tar.

All the programs we've seen thus far have been pretty basic 2 or 3 instruction affairs. What if we wanted to create something a little more complex, say, calculating the factorial of an input number?

This would require multiplying the number, n, times n - 1, and then multiplying that product times n - 2, and so on until we reach 1.

If n is not known beforehand, there is no easy way to do this via the techniques we've learned so far. In order to make these calculations, we need to iteratively perform the same calculation, n * (n - 1), over and over until n -1 = 1.

The C looping constructs allow us to perform these types of iterative calculations. In this module, we'll look at the first 2 looping types, do & while, and in our next module, we'll learn the for loop, and how to use them all to solve for factorial.

The do & while loops

Below is an interactive C program showing the use of a while loop; move your mouse over any piece of code to find out more about it.

Take a look at the same program, using a do loop instead; once again, move your mouse over any portion of the C code for more information about what's going on.

 

For a line-by-line analysis of these two types of loops, click here.

 


Continue to the Apply Section ->

Website by Joshua Bleier