Conditionals are one broad type of control structure and loops are the other. The C language supports two loop formats: while (and its sibling do…while) and for. Each loop type accomplishes the same thing—repeatedly performing some statements for a certain duration—but in slightly different ways.
The while loop is like an if conditional in that it checks a condition and then executes some statements if it's true:
while (condition) {
/* Do whatever. */
}
Once the loop has successfully executed its statements, it will then recheck the condition. If the condition is still true, the process will be repeated. If the condition is false, the execution of the loop is over and the program will continue running (Figure 4.13).
A common enough mistake programmers make is to create a loop whose condition will never be false. This creates an infinite loop, resulting in an application that will just run and run. Therefore, you should ensure that something occurs within the loop so that the condition will eventually be false.
This example will use a while loop to help calculate the factorial of a number. In simplest terms, the factorial (represented in math by the exclamation mark) is the sum of the multiplication of every number between 1 and the number. So,
5! = 1 * 2 * 3 * 4 * 5; // 120 3! = 1 * 2 * 3; // 6
1. | Create a new, blank C project in your text editor or IDE. | |
2. | Add the initial comments and code (Script 4.6): /* factorial.c - Script 4.6 */ #include <stdio.h> int main (void) { Script 4.6. A while loop is used to help calculate the factorial of a number. The loop continues to execute as long as the multiplier variable is less than or equal to the num variable. | |
3. | Establish the required variables: unsigned int num = 5; unsigned int sum = 1; unsigned int multiplier = 1; This application makes use of three unsigned integers, each of which is initialized to a set value. The first, num, represents the number whose factorial is being determined (for example, 5). The second, sum, will be the total of that factorial (eventually reaching 120 if num is 5). The third, multiplier, will be used in calculating the factorial. | |
4. | Start the while loop: while (multiplier <= num) { The factorial will be calculated by multiplying every number from 1 to num. The calculation itself will take place within the loop, so all the loop's condition has to do is check that the multiplier, which starts at 1, is still less than or equal to the number. If it is, the calculation should take place. Once the multiplier is greater than the value of num, no more calculations should be done. | |
5. | Perform the calculation: sum *= multiplier; Using the multiplication assignment operator, the sum variable is set to be the value of sum times multiplier. On the first iteration of the loop, sum will be equal to 1 (1 * 1). On the second iteration, it will be equal to 2 (1 * 2). On the third, it will be six (2 * 3); on the fourth, 24 (6 * 4); and on the fifth and final iteration (if num is 5), 120 (24 * 5).
| |
6. | Increase the value of multiplier by 1: ++multiplier; In a way, this is the most critical line in the loop. If you fail to increase the value of multiplier, then the initial condition will never be false and the loop will run endlessly. | |
7. | Complete the while loop: } // End of loop. As your code becomes more complex, commenting the end of conditionals and other control structures improves legibility. | |
8. | Print the results of the calculations: printf ("The factorial of %u is %u. ", num, sum); The printf() statement prints both the initial number and the result of the calculations. | |
9. | Complete the main() function: getchar(); return 0; } | |
10. | Save the project as factorial.c. | |
11. | Compile and debug, as necessary. | |
12. | Run the executable application (Figure 4.14). Figure 4.14. Running the application shows the calculated factorial of the number 5. | |
13. | For comparison, change the value of num, recompile, and rerun the application (Figure 4.15). Figure 4.15. By changing only the num value, the application will continue to accurately determine the factorials. |
✓ Tips
There is a variation on the while loop, called the do…while loop. The main difference is that the condition is tested after the loop has already been run once, so this control structure will always be executed at least once. The syntax is
do { /* statements */ } while (condition);
In Chapter 6, “Working with Input and Output,” you'll learn how to use the while loop to continually take keyboard input.
The factorial application can also be a good demonstration of the problems with variable overflow (see Chapter 3, “Working with Numbers”). When creating factorials you can quickly and easily eclipse the possible range of a number type.