The for Loop


The for loop was introduced in Chapter 2. Here, it is examined in detail. You might be surprised at just how powerful and flexible the for loop is. Let’s begin by reviewing the basics, starting with the most traditional forms of the for.

The general form of the for loop for repeating a single statement is

 for(initialization; condition; iteration) statement;

For repeating a block, the general form is

 for(initialization; condition; iteration) {   statement sequence }

The initialization is usually an assignment statement that sets the initial value of the loop control variable, which acts as the counter that controls the loop. The condition is an expression of type bool that determines whether the loop will repeat. The iteration expression defines the amount by which the loop control variable will change each time the loop is repeated. Notice that these three major sections of the loop must be separated by semicolons. The for loop will continue to execute as long as the condition tests true. Once the condition becomes false, the loop will exit, and program execution will resume on the statement following the for.

The for loop can proceed in a positive or negative fashion, and it can change the loop control variable by any amount. For example, the following program prints the numbers 100 to 100, in decrements of 5:

 // A negatively running for loop. using System; class DecrFor {   public static void Main() {     int x;     for(x = 100; x > -100; x -= 5)       Console.WriteLine(x);   } }

An important point about for loops is that the conditional expression is always tested at the top of the loop. This means that the code inside the loop may not be executed at all if the condition is false to begin with. Here is an example:

 for(count=10; count < 5; count++)   x += count; // this statement will not execute

This loop will never execute because its control variable, count, is greater than 5 when the loop is first entered. This makes the conditional expression, count < 5, false from the outset; thus, not even one iteration of the loop will occur.

The for loop is most useful when you will be iterating a known number of times. For example, the following program uses two for loops to find the prime numbers between 2 and 20. If the number is not prime, then its largest factor is displayed.

 /*    Determine if a number is prime.  If it is not,    then display its largest factor. */ using System; class FindPrimes {   public static void Main() {     int num;     int i;     int factor;     bool isprime;     for(num = 2; num < 20; num++) {       isprime = true;       factor = 0;       // see if num is evenly divisible       for(i=2; i <= num/2; i++) {         if((num % i) == 0) {           // num is evenly divisible -- not prime           isprime = false;           factor = i;         }       }       if(isprime)         Console.WriteLine(num + " is prime.");       else         Console.WriteLine("Largest factor of " + num +                           " is " + factor);     }   } }

The output from the program is shown here:

 2 is prime. 3 is prime. Largest factor of 4 is 2 5 is prime. Largest factor of 6 is 3 7 is prime. Largest factor of 8 is 4 Largest factor of 9 is 3 Largest factor of 10 is 5 11 is prime. Largest factor of 12 is 6 13 is prime. Largest factor of 14 is 7 Largest factor of 15 is 5 Largest factor of 16 is 8 17 is prime. Largest factor of 18 is 9 19 is prime.

Some Variations on the for Loop

The for is one of the most versatile statements in the C# language because it allows a wide range of variations. They are examined here.

Using Multiple Loop Control Variables

The for loop allows you to use two or more variables to control the loop. When using multiple loop control variables, the initialization and increment statements for each variable are separated by commas. For example:

 // Use commas in a for statement. using System; class Comma {   public static void Main() {     int i, j;     for(i=0, j=10; i < j; i++, j--)       Console.WriteLine("i and j: " + i + " " + j);   } }

The output from the program is shown here:

 i and j: 0 10 i and j: 1 9 i and j: 2 8 i and j: 3 7 i and j: 4 6

Here, commas separate the two initialization statements and the two iteration expressions. When the loop begins, both i and j are initialized. Each time the loop repeats, i is incremented and j is decremented. Multiple loop control variables are often convenient and can simplify certain algorithms. You can have any number of initialization and iteration statements, but in practice, more than two make the for loop unwieldy.

Here is a practical use of multiple loop control variables in a for statement. This program uses two loop control variables within a single for loop to find the largest and smallest factor of a number, in this case 100. Pay special attention to the termination condition. It relies on both loop control variables.

 /*    Use commas in a for statement to find    the largest and smallest factor of a number. */ using System; class Comma {   public static void Main() {     int i, j;     int smallest, largest;     int num;     num = 100;     smallest = largest = 1;     for(i=2, j=num/2; (i <= num/2) & (j >= 2); i++, j--) {       if((smallest == 1) & ((num % i) == 0))         smallest = i;       if((largest == 1) & ((num % j) == 0))         largest = j;     }     Console.WriteLine("Largest factor: " + largest);     Console.WriteLine("Smallest factor: " + smallest);   } }

Here is the output from the program:

 Largest factor: 50 Smallest factor: 2

Through the use of two loop control variables, a single for loop can find both the smallest and the largest factor of a number. The control variable i is used to search for the smallest factor. It is initially set to 2 and incremented until its value exceeds one half of num. The control variable j is used to search for the largest factor. Its value is initially set to one half the num and decremented until it is less than 2. The loop runs until both i and j are at their termination values. When the loop ends, both factors will have been found.

The Conditional Expression

The conditional expression controlling a for loop can be any valid expression that produces a bool result. It does not need to involve the loop control variable. For example, in the next program, the for loop is controlled by the value of done.

 // Loop condition can be any bool expression. using System; class forDemo {   public static void Main() {     int i, j;     bool done = false;     for(i=0, j=100; !done; i++, j--) {       if(i*i >= j) done = true;       Console.WriteLine("i, j: " + i + " " + j);     }   } }

The output is shown here:

 i, j: 0 100 i, j: 1 99 i, j: 2 98 i, j: 3 97 i, j: 4 96 i, j: 5 95 i, j: 6 94 i, j: 7 93 i, j: 8 92 i, j: 9 91 i, j: 10 90

In this example, the for loop iterates until the bool variable done is true. This variable is set to true inside the loop when i squared is greater than or equal to j.

Missing Pieces

Some interesting for loop variations are created by leaving pieces of the loop definition empty. In C#, it is possible for any or all of the initialization, condition, or iteration portions of the for loop to be blank. For example, consider the following program:

 // Parts of the for can be empty. using System; class Empty {   public static void Main() {     int i;     for(i = 0; i < 10; ) {       Console.WriteLine("Pass #" + i);       i++; // increment loop control var     }   } }

Here, the iteration expression of the for is empty. Instead, the loop control variable i is incremented inside the body of the loop. This means that each time the loop repeats, i is tested to see whether it equals 10, but no further action takes place. Of course, since i is incremented within the body of the loop, the loop runs normally, displaying the following output:

 Pass #0 Pass #1 Pass #2 Pass #3 Pass #4 Pass #5 Pass #6 Pass #7 Pass #8 Pass #9

In the next example, the initialization portion is also moved out of the for:

 // Move more out of the for loop. using System; class Empty2 {   public static void Main() {     int i;     i = 0; // move initialization out of loop     for(; i < 10; ) {       Console.WriteLine("Pass #" + i);       i++; // increment loop control var     }        } }

In this version, i is initialized before the loop begins, rather than as part of the for. Normally, you will want to initialize the loop control variable inside the for. Placing the initialization outside of the loop is generally done only when the initial value is derived through a complex process that does not lend itself to containment inside the for statement.

The Infinite Loop

You can create an infinite loop (a loop that never terminates) using the for by leaving the conditional expression empty. For example, the following fragment shows the way many C# programmers create an infinite loop:

 for(;;) // intentionally infinite loop {   //... }

This loop will run forever. Although there are some programming tasks, such as operating system command processors, that require an infinite loop, most “infinite loops” are really just loops with special termination requirements. (See “Using break to Exit a Loop,” later in this chapter.)

Loops with No Body

In C#, the body associated with a for loop (or any other loop) can be empty. This is because a null statement is syntactically valid. Bodyless loops are often useful. For example, the following program uses a bodyless loop to sum the numbers 1 through 5:

 // The body of a loop can be empty. using System; class Empty3 {   public static void Main() {     int i;     int sum = 0;     // sum the numbers through 5     for(i = 1; i <= 5; sum += i++) ;     Console.WriteLine("Sum is " + sum);   } }

The output from the program is shown here:

 Sum is 15

Notice that the summation process is handled entirely within the for statement, and no body is needed. Pay special attention to the iteration expression:

 sum += i++

Don’t be intimidated by statements like this. They are common in professionally written C# programs and are easy to understand if you break them down into their parts. In words, this statement says “add to sum the value of sum plus i, then increment i.” Thus, it is the same as this sequence of statements:

 sum = sum + i; i++;

Declaring Loop Control Variables Inside the for Loop

Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for. For example, the following program computes both the summation and the factorial of the numbers 1 through 5. It declares its loop control variable i inside the for:

 // Declare loop control variable inside the for. using System; class ForVar {   public static void Main() {     int sum = 0;     int fact = 1;     // Compute the factorial of the numbers 1 through 5.     for(int i = 1; i <= 5; i++) {       sum += i;  // i is known throughout the loop       fact *= i;     }     // But, i is not known here.     Console.WriteLine("Sum is " + sum);     Console.WriteLine("Factorial is " + fact);   } }

When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. (That is, the scope of the variable is limited to the for loop.) Outside the for loop, the variable will cease to exist. Thus, in the preceding example, i is not accessible outside the for loop. If you need to use the loop control variable elsewhere in your program, you will not be able to declare it inside the for loop.

Before moving on, you might want to experiment with your own variations on the for loop. As you will find, it is a fascinating loop.




C# 2.0(c) The Complete Reference
C# 2.0: The Complete Reference (Complete Reference Series)
ISBN: 0072262095
EAN: 2147483647
Year: 2006
Pages: 300

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