For Loops

From CompSciWiki
Jump to: navigation, search

COMP 1010 Home > Loops


Introduction

For loops are a more specialized form of loop when compared to the while loop. Generally, for loops are used when the number of iterations is known before the loop is executed.

Structured Looping

In the previous section, we discussed while loops, which were loops based on a boolean condition. The loop kept repeating while the condition evaluated to true, and execution continued after the loop body when the condition evaluated to false. While loops are able to express a wide variety of looping conditions, but sometimes we don't need such a variety. Some loops are relatively straightforward. They tell the program to "do something, some number of times". Often, this "number of times" is known beforehand, so we know how many times the loop body is supposed to execute.

As an example, imagine that you are writing a program that needs to read in ten numbers (this could be ten grades in a course). If this is the case, we need a loop that will always execute ten times. For this type of job, we can use a for loop, which is more structured than a while loop.

Elements of a For Loop

In its simplest form, a for loop will use a control variable, which will keep track of the number of times we have been through the loop. A for loop requires you to specify three conditions:

  1. An initial value for the loop variable: What value does the variable start at?
  2. A test condition for the loop variable: Which variable value does the loop stop at?
  3. An update condition for the loop variable: How do we update the loop variable each time through the loop?

A for loop will also contain a loop body, which is the same as in a while loop: it's the sequence of statements that gets executed over and over.

Syntax

The general form of a for loop is:

 for(initializer; condition; increment) {
   statements;
   ... 
} 

As an example, here is a basic for loop:

 int i;

for(i = 0 ; i < 20 ; i++) {
   System.out.println(i);
} 
  • Initializer: This is where you initialize the control variable that controls the flow (number of iterations) of the loop. In most cases this will be an int with the value of 0. NOTE! this must be followed by a semicolon.
    • In the example, this is the statement i=0, which sets the value of the loop variable i to zero.
  • Condition: This determines how many iterations the loop will execute. The loop will continue to run while the condition is true. The condition always contains the control variable being compared. NOTE! this must be followed by a semicolon. Examples of test conditions can be found at test condition.
    • In the example, the test condition i<20 says that the loop will continue operating while i is less than twenty.
  • Increment: This determines how the control variable is modified after every iteration of the loop. The idea is that after an iteration, you will be one step closer to making your condition false than you were on the previous iteration. The most common increment value is i++. Important Note: The increment should be the only statement in the for loop that modifies the value of the control variable. If you break this rule, the for loop could behave in unexpected ways.
    • In the example, the increment i++ says "each time through the loop, increase i by one".

So, we can view the example as saying:

  1. Start i at zero.
  2. Keep going until i >= 20.
  3. After every iteration, increase i by one.

In other words, the loop will execute for values of i=0,1,2,...,19.

The sequence of actions in a for loop is as follows:

  1. When the for loop is first encountered, the initialization occurs.
  2. Before the loop body is executed, the loop condition is tested. if the condition is true, the loop body is executed, otherwise, skip the body and continue after the loop. This is the same as while loops: the condition is tested before the loop is run. So a for loop can execute zero or more times, like a while loop.
  3. After the body is executed, perform the increment operation, then return to the test condition.

Examples

Example 1: Basic for loop

Here is one of the most basic examples of a for loop:

  • Initializer: i = 0;
  • Condition: Loop while i is less than 10
  • Increment: i++ (i = i + 1)
 int i;

for( i = 0 ; i < 10 ; i++ )
{
   System.out.print(i);
} 

What will this generate? Answer


Example 2: Changing the increment

Here is something you might see on an exam:

  • Initializer: i = 0;
  • Condition: Loop while i is less than 100
  • Increment: i = i + 10;
 What is the result of the following block of code? To find the solution, keep track of each int through every iteration. 

int i = 0;
int j = 0;
int k = 2;

for( i = 0 ; i < 100 ; i = i + 10 )
{
   j += ( k * i );
}
System.out.println(j); 

What will this generate? Hint: Make sure to be aware of the condition. When it evaluates to false, the loop will not iterate any more.

Answer


Example 3: Decrementing the loop variable

This simple example shows that loops do not have to start at zero and work their way up, the control variable can be decremented instead of incremented.

  • Initializer: i = 10;
  • Condition: Loop while i is greater than or equal to 0.
  • Increment: i-- (i = i - 1)
 int i;

for( i = 10 ; i >= 0 ; i-- )
{
   System.out.print(i);
} 

What will this generate? Answer

Common Pitfalls

Error: not declaring the control variable

The control variable is a variable like any other, so it needs to be declared. For instance, if you write

 for( i = 9 ; i > 0 ; i-- )
{
   System.out.print(i);
} 

Without the declaration int i; at the top of your program, the program will not compile. In Java, it is possible to declare the loop variable inside the actual for loop:

 for(int i = 9 ; i > 0 ; i-- )
{
   System.out.print(i);
} 

Notice that the declaration here happens during the initialization portion of the for loop. This is typically done when you have a throwaway control variable that is used within the loop but nowhere else. When declared this way, the control variable can only be used inside the loop body. That is, the scope of the control variable is restricted to the for loop (see Scope for more info). Compare the following two examples:


Example 1: Separate declaration. Example 2: No separate declaration.
 int i;
for(i = 0 ; i < 20 ; i++) {
   System.out.println(i);
}

System.out.println(i); 
 for(int j = 0 ; j < 20 ; j++) {
   System.out.println(j);
}

System.out.println(j); 

Example 1 will compile, and the last line of output will be 19 (since the loop exited when i=19, this is the value of i right after the loop.) On the other hand, Example 2 will not compile: j is only accessible within the loop body, so trying to print it right after the loop will result in a compile-time error.


Error: Infinite loops

A common error when writing for loops is having a disagreement between your initialization, update and test condition which leads to an infinite loop. Here's an example:

 for (int i = 0; i < 100; i--) {
 // loop body goes here.
} 

This loop will begin with i=0 and then execute the loop body, but after completion, i is 'decremented: its new value is -1. Since this is also less than 100, the loop continues to iterate, and the value of i changes to -2,-3,-4,... and you have an infinite loop. Another example which gives an infinite loop would be for (int i = 100; i > 0 ; i++): i starts at 100 and increases, so it is always greater than zero and the condition always evaluates to 'true'. Infinite loops can also occur through modifying the loop variable in the loop body, which is covered in the next section.

Error: Modifying the loop variable

We've mentioned this before, but it's worth saying again: never modify the control variable of a for loop within the loop. Here's an example:

 for (int i=0; i<10; i++) {
  System.out.println(i);
  i--;
} 

This loop will start with i=0 and then print a line of output. Then, i will be decreased, getting the value i=-1. Finally, after the execution of the loop body is completed, the increment occurs, giving i=0 and the loop starts again. This happens again and again, and you get an infinite loop.

Summary

  • Use a for loop when you know how many times the loop body should be executed.
  • Use a while loop when you do not know how many times the loop body should be executed.
  • For loops consist of (in order)
  1. Initializer with semicolon.
  2. Condition with semicolon.
  3. Increment without semicolon.
  • Do not alter the increment variable inside the loop as it will cause unexpected results.
Previous Page: Do-While Loops Next Page: Nested Loops