The for Loop

I l @ ve RuBoard

The for Loop

The for loop gathers all three actions into one place. By using a for loop, you can replace the preceding program with the one shown in Listing 6.9.

Listing 6.9 The sweetie2.c program.
 /* sweetie2.c -- a counting loop using for */ #include <stdio.h> #define NUMBER 22 int main(void) {   int count;   for (count = 1; count <= NUMBER; count++)        printf("Be my Valentine!\n");   return 0; } 

The parentheses following the keyword for contain three expressions separated by two semicolons. The first expression is the initialization. It is done just once, when the for loop first starts. The second expression is the test condition; it is evaluated before each potential execution of a loop. When the expression is false (when count is greater than NUMBER ), the loop is terminated . The third expression, the change or update, is evaluated at the end of each loop. Listing 6.9 uses it to increment the value of count , but it needn't be restricted to that use. The for statement is completed by following it with one simple or compound statement. Each of the three control expressions is a full expression, so any side effects in a control expression, such as incrementing a variable, take place before the program evaluates another expression. Figure 6.3 summarizes the structure of a for loop.

Figure 6.3. Structure of a for loop.
graphics/06fig03.jpg

To show another example, Listing 6.10 uses the for loop in a program that prints a table of cubes.

Listing 6.10 The for_cube.c program.
 /* for_cube.c -- using a for loop to make a table of cubes */ #include <stdio.h> int main(void) {   int num;   printf("    n   n cubed\n");   for (num = 1; num <= 6; num++)      printf("%5d %5d\n", num, num*num*num);   return 0; } 

Listing 6.10 prints the integers 1 through 6 and their cubes.

 n   n cubed     1     1     2     8     3    27     4    64     5   125     6   216 

The first line of the for loop tells us immediately all the information about the loop parameters: the starting value of num , the final value of num , and the amount that num increases on each looping.

Using for for Flexibility!

Although the for loop looks similar to the FORTRAN DO loop, the Pascal FOR loop, and the BASIC FOR...NEXT loop, it is much more flexible than any of them. This flexibility stems from how the three expressions in a for specification can be used. So far, you have used the first expression to initialize a counter, the second expression to express the limit for the counter, and the third expression to increase the value of the counter by 1. When used this way, the C for statement is very much like the others we have mentioned, but there are many more possibilities. Here are nine variations:

  1. You can use the decrement operator to count down instead of up.

     #include <stdio.h> int main(void)  {   int secs;      for (secs = 5; secs > 0; secs--)        printf("%d seconds!\n", secs);   printf("We have ignition!\n");   return 0;   } 

    Here is the output:

     5 seconds! 4 seconds! 3 seconds! 2 seconds! 1 seconds! We have ignition! 
  2. You can count by twos , tens, and so on, if you want:

     #include <stdio.h> int main(void)  {   int n;             /* count by 13s */      for (n = 2;  n < 60; n = n + 13)        printf("%d \n", n);   return 0;   } 

    This would increase n by 13 during each cycle, printing the following:

     2 15 28 41 54 
  3. You can count by characters instead of by numbers :

     #include <stdio.h> int main(void) {   char ch;      for (ch = 'a'; ch <= 'z'; ch++)        printf("The ASCII value for %c is %d.\n", ch, ch);   return 0; } 

    An abridged output looks like this:

     The ASCII value for a is 97. The ASCII value for b is 98. ... The ASCII value for x is 120. The ASCII value for y is 121. The ASCII value for z is 122. 

    The program works because characters are stored as integers, so this loop really counts by integers anyway.

  4. You can test some condition other than the number of iterations. In the for_cube program, you can replace

     for (num = 1; num <= 6; num++) 

    with

     for (num = 1; num*num*num <= 216; num++) 

    You would use this test condition if you were more concerned with limiting the size of the cube than with limiting the number of iterations.

  5. You can let a quantity increase geometrically instead of arithmetically; that is, instead of adding a fixed amount each time, you can multiply by a fixed amount:

     #include <stdio.h> int main(void)  {   double debt;      for (debt = 100.0; debt < 150.0; debt = debt * 1.1)        printf("Your debt is now $%.2f.\n", debt);   return 0;   } 

    This program fragment multiplies debt by 1.1 for each cycle, increasing it by 10% each time. The output looks like this:

     Your debt is now 0.00. Your debt is now 0.00. Your debt is now 1.00. Your debt is now 3.10. Your debt is now 6.41. 
  6. You can use any legal expression you want for the third expression. Whatever you put in will be updated for each iteration.

     #include <stdio.h> int main(void)  {     int x;     int y = 55;          for (x = 1; y <= 75; y = (++x * 5) + 50)         printf("%10d %10d\n", x, y);     return 0;  } 

    This loop prints the values of x and of the algebraic expression ++x * 5 + 50 . The output looks like this:

     1         55          2         60          3         65          4         70          5         75 

    Notice that the test involved y , not x . Each of the three expressions in the for loop control can use different variables . (Note that although this example is valid, it does not show good style. The program would have been clearer if we hadn't mixed the updating process with an algebraic calculation.)

  7. You can even leave one or more expressions blank (but don't omit the semicolons). Just be sure to include within the loop itself some statement that eventually causes the loop to terminate.

     #include <stdio.h> int main(void)  {   int ans, n;      ans = 2;   for (n = 3; ans <= 25; )        ans = ans * n;   printf("n = %d; ans = %d.\n", n, ans);   return 0;  } 

    Here is the output:

     n = 3; ans = 54. 

    The loop keeps the value of n at 3. The variable ans starts with the value 2 , then increases to 6 and 18 , and obtains a final value of 54 . (The value 18 is less than 25, so the for loop goes through one more iteration, multiplying 18 by 3 to get 54.) Incidentally, an empty middle control expression is considered to be true, so the following loop goes on forever:

     for (; ; )      printf("I want some action\n"); 
  8. The first expression need not initialize a variable. It could, instead, be a printf() statement of some sort . Just remember that the first expression is evaluated or executed only once, before any other parts of the loop are executed.

     #include <stdio.h> int main(void) {    int num;          for (printf("Keep entering numbers!\;n"); num != 6;  )            scanf("%d", #);    printf("That's the one I want!\n");    return 0; } 

    This fragment prints the first message once and then keeps accepting numbers until you enter a 6:

     Keep entering numbers! 3 5 8 6 That's the one I want! 
  9. The parameters of the loop expressions can be altered by actions within the loop. For example, suppose you have the loop set up like this:

     for (n = 1; n < 10000; n = n + delta) 

    If, after a few iterations, your program decides that delta is too small or too large, an if statement (refer to Chapter 7, "C Control Statements: Branching and Jumps" ) inside the loop can change the size of delta . In an interactive program, delta can be changed by the user as the loop runs.

In short, the freedom you have in selecting the expressions that control a for loop makes this loop able to do much more than just perform a fixed number of iterations. The power of the for loop is enhanced further by the operators we will discuss shortly.

Summary: The for Statement

Keyword:

 for 

General Comments:

The for statement uses three control expressions, separated by semicolons, to control a looping process. The initialize expression is executed once, before any of the loop statements are executed. Then the test expression is evaluated, and if it is true (or nonzero), the loop is cycled through once.

Then the update expression is evaluated, and it is time to check the test expression again. The for statement is an entry-condition loop ”the decision to go through one more pass of the loop is made before the loop is traversed. Therefore, it is possible that the loop is never traversed. The statement part of the form can be a simple statement or a compound statement.

Form:

 for (initialize ; test ; update)      statement 

The loop is repeated until test becomes false or zero.

Example:

 for (n = 0;  n < 10 ; n++)       printf(" %d %d\n", n, 2 * n + 1); 
I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net