Difference between revisions of "For Loops"

From CompSciWiki
Jump to: navigation, search
(first attempt at rewrite.)
Line 1: Line 1:
 
{{1010Topic|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.|Chapter_TOC=[[Loops]]|Overview=You will learn common usages for the For loop as well as common things to avoid with the For loop}}
 
{{1010Topic|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.|Chapter_TOC=[[Loops]]|Overview=You will learn common usages for the For loop as well as common things to avoid with the For loop}}
  
 +
 +
==Structured Looping==
 +
 +
In the previous section, we discussed [[While_Loops|while loops]], which were loops based on a boolean condition. The loop kept repeating while the condition was true, and execution continued after the loop body when the condition became 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 easy: do something (or something very similar) some number of times. And 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 (ten grades in a course, for example). Then 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 loop 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:
 +
# an initial value for the loop variable: what value does the variable start at?
 +
# a test condition for the loop variable: which value does the loop stop at?
 +
# 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 for loop: it's the sequence of statements that gets executed over and over.
  
 
==Syntax==
 
==Syntax==
Line 6: Line 21:
  
 
<pre>
 
<pre>
for(initializer; condition; increment)
+
for(initializer; condition; increment) {
   statement;
+
   statements;
 
+
  ...
which looks something like:
+
}
 +
</pre>
  
for(i = 0 ; i < 20 ; i++)
+
As an example, here is a basic for loop:
 +
<pre>
 +
for(i = 0 ; i < 20 ; i++) {
 
   System.out.println(i);
 
   System.out.println(i);
 
+
}
 
</pre>
 
</pre>
  
*'''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.  
+
*'''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.
'''NOTE!''' this must be followed by a semicolon.
+
** In the example, this is the statement <tt>i=0</tt>, which sets the value of the loop variable <tt>i</tt> 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.  
+
*'''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]].
'''NOTE!''' this must be followed by a semicolon. Examples of test conditions can be found at [[test condition]].
+
** In the example, the test condition <tt>i&lt;20</tt> says that the loop will continue operating while <tt>i</tt> is less than twenty.  
  
*'''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++;
+
*'''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.
 +
**In the example, the increment <tt>i++</tt> says "each time through the loop, increase <tt>i</tt> by one".
  
*'''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.
+
So, we can view the example as saying
 +
# start <tt>i</tt> at zero.
 +
# every time through the loop, increase <tt>i</tt> by one.
 +
# keep going until <tt>i >= 20</tt>.
 +
In other words, the loop will execute for values of <tt>i</tt>=0,1,2,...,19.
  
 
==Examples==
 
==Examples==
'''Eg. 1'''
+
 
 +
===Example 1: Basic for loop===
  
 
Here is one of the most basic examples of a for loop:
 
Here is one of the most basic examples of a for loop:
 
   
 
   
*Initializer: i = 0;
+
*Initializer: <tt>i = 0;</tt>
*Condition: Loop while "i" is less than 10
+
*Condition: Loop while <tt>i</tt> is less than 10
*Increment: i++ (i = i + 1)
+
*Increment: <tt>i++</tt> (<tt>i = i + 1</tt>)
 
<pre>
 
<pre>
 
int i;
 
int i;
Line 46: Line 70:
  
  
'''Eg. 2'''
+
===Example 2: Changing the increment===
 +
 
 
Here is something you might see on an exam:
 
Here is something you might see on an exam:
  
*Initializer: i = 0;
+
*Initializer: <tt>i = 0</tt>;
*Condition: Loop while i is less than 100
+
*Condition: Loop while <tt>i</tt> is less than 100
*Increment: i = i + 10;
+
*Increment: <tt>i = i + 10;</tt>
  
 
<pre>
 
<pre>
Line 70: Line 95:
  
  
'''Eg. 3'''
+
===Example 3: Decrementing the loop variable===
 +
 
 
Another simple example to show you that loops do not have to start at zero and work their way up.
 
Another simple example to show you that loops do not have to start at zero and work their way up.
  
*Initializer: i = 10;
+
*Initializer: <tt>i = 10;</tt>
*Condition: Loop while i is greater than or equal to 0.
+
*Condition: Loop while <tt>i</tt> is greater than or equal to 0.
*Increment: i-- (i = i - 1);
+
*Increment:<tt> i--</tt> (<tt>i = i - 1</tt>)
  
 
<pre>
 
<pre>

Revision as of 15:11, 9 August 2010

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}}}


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 was true, and execution continued after the loop body when the condition became 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 easy: do something (or something very similar) some number of times. And 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 (ten grades in a course, for example). Then 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 loop 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 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 for 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:

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 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.
    • 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. every time through the loop, increase i by one.
  3. keep going until i >= 20.

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

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?

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


Example 3: Decrementing the loop variable

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.