For Loops

From CompSciWiki
Revision as of 20:04, 6 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.

  • Note to self make sure not to change "i" inside loop.

Syntax

The general form of a for loop is:

for(initializer; condition; increment)
   statement;
  • Initializer: This is where you initialize the 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 initializer variable being compared. NOTE! this must be followed by a semicolon. Examples of test conditions can be found at test condition.
  • Increment:

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 = 0;

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

Result: 0123456789


Eg. 2

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

Here is something you might see on an exam:

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 = j + (k * i);
}
System.out.println(j);

Result: 900

Summary

For Loop or While Loop?

  • 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 Loop Form 1. Initializer with semicolon. 2. Condition with semicolon. 3. Increment without semicolon.

Back to Loops