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 sequential programming techniques we've learned thus 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. Let's take a look at each of the three using simple examples, and then investigate how to use them to solve for factorial.
The do & while loops
The do & while loops are the most straight-forward of the 3 looping methods, and in fact are almost exactly the same; they perform as follows:
- The do loop -
- do everything in the curly braces while a condition holds true. It looks like this...
do {
action1
action2
.
.
.
actionn
} while (condition)
where
- each action is a C instruction terminating with a semi-colon,
- condition is an operation that returns TRUE (1) or FALSE (0).
- The while loop -
- while a condition holds true, perform everything in the curly braces. It looks like this...
while (condition) {
action1
action2
.
.
.
actionn
}
As you can see, the difference between these two is only where the TRUE-FALSE condition is tested;
- in the do loop, it takes place after the instructions in the curly braces, guaranteeing that those instructions take place at least once.
- in the while loop, the condition is tested before the instructions in the curly braces, which means that if the condition is FALSE, those instructions may never be performed.
Let's take a look at a simple example for each of these. Decompress module2.tar, and cd into the week2 directory.
In the LOOP_BASICS subdirectory of module2, you'll find 2 programs that do almost exactly the same iteration; do.c is the do loop version, and while.c is the while loop version.
Here's the do.c version...
#include <stdio.h>
main () {
int i,n;
printf("how many loops?\n");
scanf("%d", &n);
/* this next line initializes the value of i */
i = 0;
printf("Starting the loop...\n");
do {
printf("on loop %d of %d\n", i, n);
/* we must increase i, or this will loop forever */
i++;
} while( i < n);
}
Notice that we declare 2 integer variables, i & n. The integer i will be the iterating variable, which will be tested against n after each looping cycle.
The program next gets the number of loop iterations from the user via scanf (let's say for this example that the user inputs 2), and places into n.
At this point, after a printf statement, we start the loop, which is comprised of only 2 statements,
- one printing out the current iteration against the total number of loops, and
- the other increasing i by one (i++ is shorthand C for i = i + 1;).
This incrementation of i is critical;
if i is not increased during each loop, then this loop construct will run forever.
Finally, after the loop, is the conditional statement that tests i compared to n. After the initial loop, i becomes 1, the test i < n (at this iteration, it's 1 < 2) is TRUE, and we continue with the loop.
- The 2 loop statements are repeated; we first print out the current value of i (1) and the total n (2 in our example).
- Next, we increment i again, which now becomes 2.
The values of i and n are compared in our conditional statement after the loop, and this time i < n is 2 < 2, which is FALSE, and we terminate the loop statement. Since there are no instructions after the do loop, we end the program as well.
Let's compare this against the while version of this program in while.c. You'll notice that it is virtually identical, save for the conditional statement, which takes place before the loop is entered.
#include <stdio.h>
main() {
int i,n;
printf("how many loops?\n");
scanf("%d", &n);
/* We initialize i */
i = 0;
while (i < n) {
printf("on loop %d of %d\n", i, n);
/* Increment i or this loop will continue forever. */
i++;
};
}
For our example of the user inputting 2 for n, nothing changes;
- The iteration variable i is still set to 0 initially,
- we first test i against n before entering the loop (0 < 2); it is TRUE,
- so we enter the loop and print out the current iteration versus the total,
- then we increment i (i++;), so i becomes 1.
- We then go back to the beginning and test i to n again (1 < 2), which is still TRUE,
- so we enter the loop again, printing out the current iteration i (1) versus the total (2).
- We again increment i so it's now 2, exit the loop, and go back to the beginning,
- where we test i against n again (2 < 2). Now this conditional is FALSE, so we do NOT enter the loop, but instead continue past it, and terminate the program.
So, when would there be any difference in execution between the do loop version and the while loop version?
Let's say that instead of 2, the user input 0 for the total number of iterations:
- For the do loop version,
- we enter the loop without testing n (Set by the user to 0) to the initial value of i, which is also 0. So we perform the loop instructions,
- first printing the loop iteration value versus the total (0 to 0),
- then incrementing i so it is now 1.
- Only then do we perform the conditional test; i < n is FALSE, since i is now 1 and n is 0, so we do not loop again, and terminate the program.
- For the while loop version,
- We TEST the value of i (initialized to 0) to the value of n (set by the user to 0) BEFORE we enter the loop.
- Since i is equal to n, this test is FALSE, and we do not perform the loop statements at all, terminating the program instead.
This last example illustrates that the one small difference between the do and while looping constructs can be critical; the programmer should consider whether he or she wishes to have the instructions within the loop performed once for sure (As it will for the do loop), or possibly not at all (Which may be the case, depending on initial values, in the while loop).
After you wrap up the material in this module, we'll cover the for loop, then discuss the useful concept of nested loops; finally, we'll provide some examples that show how effective these looping constructs can be in automating repetitive, incremental calculations.
Continue to the Apply Section ->