Difference between revisions of "Nested loops"

From CompSciWiki
Jump to: navigation, search
(Putting it All Together)
 
(14 intermediate revisions by 4 users not shown)
Line 1: Line 1:
==Introduction==
+
{{1010Topic|Introduction=Nested loops are just one loop working inside of another loop. The best way to start learning about nested loops is to look at an example using matrices.|Overview=Nested loops allow more complex processing of data. Here we will discuss a simple case of a matrix and how nested loops help to make the code for processing a matrix easier to read.|Chapter_TOC=[[Loops]]}}
A nested loop is simply just more than one loop inside another. There are no special rules for using nested loops, you only need to take them one at a time. This may sound complicated but after you start using nested loops it will seem like second nature. The best way to start learning about nested loops is to look at an example using matrices.
+
  
 
==Matrix Example==
 
==Matrix Example==
Line 8: Line 7:
 
A simple matrix with two rows and three columns.
 
A simple matrix with two rows and three columns.
  
012
+
0 1 2
345
+
3 4 5
 
</pre>
 
</pre>
  
Now suppose you wanted to print that matrix out in a program by simply using loops. An easy solution would be to use double nested for loops such as:
+
Now suppose you wanted to print that matrix out in a program by simply using loops. An easy solution would be to use a [[For]] loop nested in another [[For]] loop.
  
 
<pre>
 
<pre>
Line 18: Line 17:
 
int count = 0;
 
int count = 0;
  
for(row = 0; row < 2; row++)
+
for( row = 0 ; row < 2 ; row++ )
 
{
 
{
     for(column = 0; column < 3; column++)
+
     for( column = 0 ; column < 3 ; column++ )
 
     {
 
     {
 
           System.out.print(count);
 
           System.out.print(count);
Line 33: Line 32:
 
===Outer Loop===
 
===Outer Loop===
 
<pre>
 
<pre>
for(row = 0; row < 2; row++)
+
for( row = 0 ; row < 2 ; row++ )
 
{
 
{
 
  ...
 
  ...
Line 43: Line 42:
 
===Inner Loop===
 
===Inner Loop===
 
<pre>
 
<pre>
for(column = 0; column < 3; column++)
+
for( column = 0 ; column < 3 ; column++ )
 
{
 
{
 
     System.out.print(count);
 
     System.out.print(count);
Line 59: Line 58:
  
 
===Putting it All Together===
 
===Putting it All Together===
* The outer loop will perform whatever is inside it two times.
+
* The outer loop will perform whatever is inside two times.
 
* The contents of the outer loop is another loop.  
 
* The contents of the outer loop is another loop.  
 
* The inner loop prints out the value of ''count'' in sets of three.
 
* The inner loop prints out the value of ''count'' in sets of three.
 
+
* Therefore the inner loop will be executed two times with a total of 6 iterations (3 per execution).
'''Step-by-Step'''
+
#
+
  
 
==Other Uses==
 
==Other Uses==
An important note to remember is that you can mix and match different types of loops together to create nested loops.
+
* When you learn about multi-dimensional arrays, double [[for]] loops will come in handy (see Matrix Example).
 +
* You can mix and match different types of loops together to create nested loops.
  
 
Example:
 
Example:
Line 88: Line 86:
 
</pre>
 
</pre>
  
* When you learn about multi-dimensional arrays, double [[for]] loops will come in handy (see Matrix Example).
+
==Warnings==
 +
Quite often when using for loops we get used to using the variable i as a counter.  When you have nested For loops you cannot use the same control variable for both loops. You must have separate control variables for each nested loop so that each loop does not control the other one. 
  
==Example Program==
+
The following is a common error:
 
<pre>
 
<pre>
/**********************************
+
int i;
* NestedX:
+
int j;
* Prints out a fancy "ascii art"
+
for( i = 0 ; i < 10 ; i++ )
* picture in the shape of an X where
+
* the user supplies the size of the X.
+
***********************************/
+
 
+
import javax.swing.*;
+
 
+
public class NestedX
+
 
{
 
{
public static void main(String[] args)
+
    for( j = 0 ; j < 10 ; i++ ) //notice the i++ should be j++, this is just one spot a mistake may be made
{
+
    {
int size = 0;
+
        ..(some code)
int i, j;
+
    }
 +
}
 +
</pre>
  
// Keep asking for input until it is greater or equal to 3.
+
==Programming Questions==
while(size < 3)
+
'''Program 1'''
{
+
Create a program that will print out ascii art in the shape of an X. The program will prompt the user for input in the form of a number of at least size 3. For example if the user typed the number 5 your result would look like:
size = Integer.parseInt(JOptionPane.showInputDialog("Enter a number greater or equal to 3"));
+
}
+
  
for(i = 0; i < size; i++)
+
<pre>
{
+
*  *
for (j = 0; j < size; j++)
+
* *
{
+
  *
if(i == j)
+
* *
{
+
*   *
System.out.print("*");
+
}
+
else if(j == (size - (i + 1)))
+
{
+
System.out.print("*");
+
}
+
else
+
{
+
System.out.print(" ");
+
}
+
}
+
System.out.println();
+
}
+
 
+
System.out.println("\n~~~End of processing~~~");
+
System.exit(0);
+
 
+
}// end main
+
}// end NestedX
+
 
</pre>
 
</pre>
 
+
[[Nested_Loops_Answers_1|Answer]]
 
+
'''[[Loops|Back to Loops]]'''
+

Latest revision as of 23:52, 5 December 2007

COMP 1010 Home > Loops


Introduction

Nested loops are just one loop working inside of another loop. The best way to start learning about nested loops is to look at an example using matrices.

   

{{{Body}}}

Matrix Example

If you have never encountered a matrix before you can think of it as rows and columns of numbers. Or you can think of a matrix as simply a table of rows and columns like so:

A simple matrix with two rows and three columns.

0 1 2
3 4 5

Now suppose you wanted to print that matrix out in a program by simply using loops. An easy solution would be to use a For loop nested in another For loop.

int row, column;
int count = 0;

for( row = 0 ; row < 2 ; row++ )
{
     for( column = 0 ; column < 3 ; column++ )
     {
          System.out.print(count);
          count++;
     }
     System.out.println();
}

The best way to describe what is happening here is to break this code up into the two loops.

Outer Loop

for( row = 0 ; row < 2 ; row++ )
{
 ...
}

We already know that a for loop will perform the same task until its test condition is met. In this example, the loop will execute the code inside two times meaning that whatever is inside this loop will be performed twice.

Inner Loop

for( column = 0 ; column < 3 ; column++ )
{
     System.out.print(count);
     count++;
}
System.out.println();

Here is a simple for loop that prints out the value of count, updates count and finishes by adding a new line once the loop's test condition is met. This loop will run three times printing out:

012

Putting it All Together

  • The outer loop will perform whatever is inside two times.
  • The contents of the outer loop is another loop.
  • The inner loop prints out the value of count in sets of three.
  • Therefore the inner loop will be executed two times with a total of 6 iterations (3 per execution).

Other Uses

  • When you learn about multi-dimensional arrays, double for loops will come in handy (see Matrix Example).
  • You can mix and match different types of loops together to create nested loops.

Example:

while(...)
{
    for(...)
    {
       for(...)
       {
            ...
       }
    }
    while(...)  
    {
        ...
    }
}

Warnings

Quite often when using for loops we get used to using the variable i as a counter. When you have nested For loops you cannot use the same control variable for both loops. You must have separate control variables for each nested loop so that each loop does not control the other one.

The following is a common error:

int i;
int j;
for( i = 0 ; i < 10 ; i++ )
{
    for( j = 0 ; j < 10 ; i++ ) //notice the i++ should be j++, this is just one spot a mistake may be made
    {
        ..(some code)
    }
}

Programming Questions

Program 1 Create a program that will print out ascii art in the shape of an X. The program will prompt the user for input in the form of a number of at least size 3. For example if the user typed the number 5 your result would look like:

*   *
 * *
  *
 * *
*   *

Answer