For Loops

From CompSciWiki
Revision as of 18:37, 7 December 2007 by Guanyun (Talk | contribs)

Jump to: navigation, search

COMP 1010 Home > Loops


Introduction

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

   

{{{Body}}}


Syntax

The general form of a for loop is:

for(initializer; condition; increment)
   statement;

which looks something like:

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.

  • 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.

  • Increment: This determines how you will modify the control variable after every iteration of the loop. The goal is that 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, your program will do unexpected things.

Examples

Eg. 1

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


Eg. 2 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?

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? Answer


Eg. 3 Another simple example to show you that loops do not have to start at zero and work their way up.

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

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

What will this generate? Answer

Summary

  • Use a for loop when you know how many times it needs to iterate.
  • Use a while loop when you do not know how many times it needs to iterate.
  • 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.