The For Loop

The final control structure we discuss in this chapter (and in the book) is the for loop. Much like while, it will perform an operation for a certain number of iterations. The syntax, though, is vastly different:

for (initial expression; conditional;
concluding expression) {
   /* Do whatever. */
}

The first time the application encounters the loop, the initial expression will be executed. Then the conditional will be checked. If true, the statements (marked by Do whatever. earlier) are run. Then, the concluding expression is executed. Finally, the condition is checked again and the process is repeated (except that the initial expression is only run the first time; see Figure 4.16). With the for loop, the concluding expression is usually responsible for ensuring that the condition becomes false at some point.

Figure 4.16. How a for loop functions is significantly different than a while loop, considering the addition of the initial and post-expressions.


A rewrite of the factorial.c example will better demonstrate this syntax and how similar for and while can be in usage.

To use the for loop

1.
Open factorial.c (Script 4.6) in your text editor or IDE.

2.
Change the name of the multiplier variable to be just i and do not set its initial value (Script 4.7):

unsigned int i;

Script 4.7. This revision of the factorial.c application (Script 4.6) replaces the while loop with a for loop.


It's standard practice in C to use the letter i as a counter in for loops. Although that's not required, this example will abide by that norm. You no longer have to initialize it (set a value) as that will happen in the for loop.

3.
Delete the entire while loop.

4.
Begin defining the for loop:

for (i = 1; i <= num; ++i) {

Upon first encountering this loop, the application will set the i variable to the value of 1. Then, if i is less than or equal to num, the loop's statements (Step 5) will be executed. After the loop's statements are executed, the i variable will be incremented by 1.

5.
Add the loop's single statement:

sum *= i;

Since the multiplier is now named i, the calculation is changed slightly. More important, though, is that the multiplier no longer has to be incremented as part of the loop's statements, since that is now part of the loop's definition (Step 4).

6.
Close the for loop:

} // End of loop.

7.
Save the file as factorial2.c.

8.
Compile, debug (as necessary), and run the application (Figure 4.17).

Figure 4.17. The factorial is now calculated using a for loop, which can be just as effective as a while loop.


9.
If you want, change the value of num, recompile, and rerun the application.

✓ Tips

  • Although the for loop often only uses three separate expressions, it's not limited to that. The first and last part of the for syntax (the initial and concluding expressions) can have multiple expressions if they are separated by commas:

    for (sum = 1, i = 1; i <= num; ++i) {...
    
  • Conversely, each of the three for loop sections is optional. The code

    for (;;) {...
    

    is perfectly valid, although it does create an infinite loop.

  • The for loop is often used with arrays to do something with each of the array's elements. This will be demonstrated in Chapter 6, “Working with Arrays.”

    Nesting Conditionals and Loops

    C allows you to nest the different control structures: place one conditional within another; put a loop within another loop; have a conditional within a loop; and so forth. When doing this, maintaining the proper syntax is crucial. Follow these suggestions when nesting any control structures:

    • Always use opening and closing curly braces to mark where control structures begin and end.

    • Indent subordinate control structures in their entirety.

    • Use comments to mark the purpose of control structures and where they conclude.

    With nested control structures, improperly balancing your curly braces is a common cause of errors. You'll see many examples of nested control structures throughout the course of this book, and every one abides by those suggestions in order to help avoid errors.


  • When nesting for loops (see the sidebar), it's quite common to use a variable called i for the first, outermost loop; j for the inner one; k for one inside of that; and so forth.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset