C Tutorial (15) : For Loop

Another type of C loop is called the for loop. A for loop offers more control than while and do-while. With a for loop, you can specify exactly how many times you want to loop; with while loops, you must continue looping as long as a condition is true.

C programs have room for all three kinds of loops. Sometimes one loop fits one program’s requirements better than another. You could use a for loop when you would then know exactly how many times to loop.

Note : By incrementing counter variables, you can simulate a for loop with a while loop. You also can simulate a while with a for! Therefore, the kind of loop you use ultimately depends on which kind you feel comfortable with at the time.

The for loop is important for controlling repeating sections of code. The format of for is a little strange:

for (startExpression; testExpression; countExpression)
 { block of one or more C statements; }

Perhaps a short example with actual code is easier to understand:

for (ctr = 1; ctr <= 5; ctr++)
{
  printf("Counter is at %d.\n", ctr);
}

Here’s how this for statement works: When the for begins, the startExpression, which is ctr = 1;, executes. The startExpression is executed only once in any for loop. The testExpression is then tested. In this example, the testExpression is ctr<= 5;. If it is true—and it will be true the first time in this code—the body of the for loop executes. When the body of the loop finishes, the countExpression is executed (ctr is incremented).

Tip : As you can see, indenting the body of a for loop helps separate the body of the loop from the rest of the program, making the loop more readable. (The same is true for the other kinds of loops, such as do-while loops.)

That’s a lot to absorb in one full swoop, even in one paragraph. Let’s make it easy. Follow the line in Figure, which shows the order in which for executes. While following the line, reread the preceding paragraph. It should then make more sense to you.

for_loop

Note : The for loop’s format is strange because of the embedded semicolons that are required. It is true that semicolons go only at the end of executable statements, but statements inside for loops are executable. For instance, the initial expression, ctr = 1;, is completed before the loop begins, as Figure shows.

Here is the very same loop written as a while statement:

ctr = 1;
while (ctr <= 5)
{
  printf("Counter is at %d.\n", ctr); 
  ctr++;
}

Tip : If you follow Figure’s guiding line and read the preceding while loop, you’ll see that the for and while do the same thing. The ctr = 1; that precedes the while is the first statement executed in the for.

A do-while loop can’t really represent the for loop because the relational test is performed before the body of the for loop and after it in the do-while.

Working with for

The for loop reads a lot like the way you speak in everyday life. Consider this statement:

For each of our 45 employees, calculate the pay and print a check.

// Loop to calculate payroll for each employee 
for (i=1; i <= employees; i++;)
{
  // Calculations for each employee follow...
}

for loops don’t always count up as the preceding two did. This for loop counts down before printing a message:

for (cDown = 10; cDown >0; cDown--)
{
 printf("%d.\n", cDown);
}

You also do not have to increase or decrease your loop counter by 1. The following for loop counts up by threes, beginning with 1:

for (i = 1; i < 18; i += 3)
{
   printf("%d ", i); // Prints 1, 4, 7, 10, 13, 16
}

The following code produces an interesting effect:

for (outer = 1; outer <= 3; outer++)
{
  for (inner = 1; inner <= 5; inner++)
  {
    printf("%d ", inner)
  }

  // Print a newline when each inner loop finishes 
  printf("\n");
}

Here is the code’s output:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5

If you put a for loop in the body of another loop, you are nesting the loops. In effect, the inner loop executes as many times as the outer loop dictates.

The for statement gives you a little more control over the loop than either while or do-while. The for statement controls a loop with a variable that is initialized and changed according to the expressions in the for statement.

  • Use a nested loop if you want to loop a certain number of times.

 

While Loop < Prev                                                           Next > Break & Continue

Advertisements

2 comments

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s