For Loops

From CompSciWiki
Revision as of 20:54, 19 March 2007 by Umwooley (Talk | contribs)

Jump to: navigation, search

Introduction

For loops perform the same functionality as most other loops as they will execute the same task over and over again until a condition is met that will stop the loop. Understanding when to use a for loop is the first thing you should know before attempting to master them. The golden rule of when to use a for loop is if you know before the loop has started how many times it needs to iterate.

Syntax

The general form of a for loop is:

for(initializer; condition; increment)
   statement;

which looks something like:

for(int 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 Node: 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

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.


Back to Loops