Lesson 4 - Iteration

TABLE OF CONTENTS: Introduction - while loops - for loops - do-while loops - Choosing the best iteration type

Introduction -

Computers are designed to perform many calculations very quickly. They are efficient and save us time. We also want to be efficient as programmers. Iteration (or looping statements) allow us to tell the computer to do something many times. There are three main types of iteration statements that we will work with:

Pre-requisites -

Before beginning this lesson you should have completed the HelloWorld2 program.  (This would give you experience using the programming environment and structuring simple programs.) You should also have a basic understanding of objects and variables (although not mastery yet.) Finally, you need an understanding of conditional logic, as it is used to decide how long to keep a loop going for.  

Goals -

  1. Students will use correct syntax when writing iteration statements in Java.
  2. Students will be able to use iteration statements within Java programs to accomplish tasks efficiently.

Section 1: While loops

These are your objectives for this section:

Given an output description and a section of code with a missing line, students will be able to fill in a while statement that would accomplish the task without producing errors. 

Given a section of code that includes a while loop, students will identify the outcome of that section of code.

In Java, we can write while loops that will make sections of code repeat as long as a condition is met. Here is how this would work.

while(condition)
     statement; 
--or--
while(condition)
{
     statement1; 
     statement2; 
     statement3; 

}

The statement(s) would only be run if the condition evaluated to true.

while(game.score < 100)
    game.playNextTurn();

In this example, if the variable score from the game object is less than 100, the playNextTurn method would be called from the game object. However if the score was equal to or above 100, the program would continue without running the playNextTurn method.

while(count < 10)
    System.out.println("The count is: "+count);

In this example, if the variable count was less than 10, the terminal window would display The count is #, since there is nothing in the loop to change the value of count, it would keep displaying forever!

Sometimes you have multiple lines of code that you want to execute within the loop. You can always group together sections of code using curly brackets { }.

int count = 1;

while(count <= 10)
{
     System.out.println("The count is: "+count);
     count = count + 1;
}

This example (above) of code would run all three statements within the curly brackets only if the condition was met. However, the example below would loop forever because the line that increases count is not included within the while loop. Remember unless you use curly brackets, the while statement ends at the semicolon.

int count = 1;

while(count <= 10)
     System.out.println("The count is: "+count);
     count = count + 1;

Practice

Find and correct the errors in the following pieces of code:

while(number = 5) 
    System.out.println("correct.");
while(number == 5) //Two equals signs to compare.
      System.out.println("correct.");
while(true);
    System.out.println("goes forever!");
while(true) //semicolon here makes it do nothing
    System.out.println("goes forever!");
// counting to five

int count = 1;

while(count <=5)

    System.out.println(count);

    count = count + 1;
// counting to five

int count = 1;

while(count <=5)
{ //Need the curly brackets to group statements.
    System.out.println(count);
    count = count + 1;
}

Section 2: For loops

These are your objectives for this section:

Given an output description and a section of code with a missing line, students will be able to fill in a for statement that would accomplish the task without producing errors. 

Given a section of code that includes a for loop, students will identify the outcome of that section of code.

In Java, we can write for loops that will make sections of code repeat until a condition is met. For loops are different than while loops in that you specify initial conditions and an iterator. Here is how this would work.

for(initial assignment ;  condition ; iterator)
     statement; 
--or--
for(initial assignment ;  condition ; iterator)
{
     statement1; 
     statement2; 
     statement3; 

}

The statement(s) would only be run if the condition evaluated to true.

for(count=0 ; count<10 ; count=count+1)
    System.out.println(count);

To evaluate this example let's look at it in stages...

So this section of code should print out the numbers from 0 to 9.

There are many things that you can change about a for loop. For example, the count varaible can have any vaid name, it can start and end at any value you choose and it can change each step up or down by any value you choose...

for(joe=20 ; joe>4 ; joe=joe-2)
    System.out.println(joe);

This would print out 20 - 18 - 16 - 14 - 12 - 10 - 8 - 6 (each on separate lines.)

Sometimes you have multiple lines of code that you want to execute within the loop. You can always group together sections of code using curly brackets { }.

for(int count=0 ; count<10 ; count=count+1)
{
     System.out.println("The count is:");
     System.out.println(count);
}

This example (above) of code would run both statements within the curly brackets each time it ran through the loopHowever, the example below would only display "The count is:" multiple times and then print the count (10) once. This is because the line that displays the count is not included within the while loop. Remember unless you use curly brackets, the while statement ends at the semicolon.

for(int count=0 ; count<10 ; count=count+1)
     System.out.println("The count is:");
     System.out.println(count);

Increment and Decrement operators

As programmers we're always looking for ways to make things easier. We want to make the computer do all the work, not us :-) Anyway, there are shortcuts whenever you want to change the value of an integer variable by one. (This often happens in for loops.)

The increment operator ++ (two plus signs) will increase an integer variable by one.

So instead of

count = count + 1;

you can use

count++;

The decrement operator -- (two minus signs) will decrease an integer variable by one.

Nested loops

Sometimes it is useful to put a loop inside another loop. This is called a nested loop. It is always legal, but you have to be really careful with your curly brackets.

for(int row=0; row<5; row++)
{
	for(int col=0; col<=row; col++) //Notice the condition is dependent on row.
	{
		System.out.print("*");
	}
	System.out.println("-");
}

Try that code out and see what it does!

Practice

What would be the output from the following pieces of code:

for(int x=0;x<3;x++) 
    System.out.println("#"+x);
#0
#1
#2
for(int x=4;x<3;x++) 
    System.out.println("#"+x);
No output, the condition is never met.
for(int x=1;x<25;x++); 
    System.out.println("#"+x);
#25
(There's a semicolon on the for statement. The loop finishes before reaching the println.)

 

Section 3: Do-while loops

This is your objective for this section:

Given an output description and a section of code with a missing line, students will be able to fill in a do-while statement that would accomplish the task without producing errors. 

Given a section of code that includes a do-while loop, students will identify the outcome of that section of code.

In Java, we can write do-while loops that will always run once and then make sections of code repeat as long as a condition is met. Here is how this would work.

do
{
	statement1; 
	statement2; 
	statement3; 

} while(condition); 

The statement(s) would always be run once and then continue to run if the condition evaluated to true.

String password = "awesome";

do
{
    System.out.println("Please enter the password");
    String entry = keyboard.next();
} while (!entry.equals(password));

In this example, the user is always asked at least once to type the password. The loop will continue to ask for the password if the password is not correct.

Section 4: Choosing the best loop for the situation

This is your objective for this section:

Given a specification, write a program that produces the correct output (e.g. a sequence or sum) based on a user input (e.g. number to count to).  The program must run without errors and produce the correct output in every possible test case.

Now you have three different types of looping statements (while, for and do-while.) You can use any of them to accomplish most everything you want to use a loop for, but typically while loops are used when the number of iterations can vary while for loops work best for a fixed number of iterations.

 

Here are a few programming challenges for you to try:

(This assignment is worth 90 points. You must complete three of the following programs)

  1. Write a program that asks the user for an integer and then prints out all of the factors of that number.
  2. Write a program that prints all of the prime numbers up to 500. (And the program has to calculate them!)
  3. Write a program that counts in Roman numerals up to 100.
  4. Write a guess the number game that plays until you get the right number. Give a hint of "too high" or "too low" after each wrong guess.

Helpful References

BlueJ

Java Au Naturel

Java API

Online Tutorial - LandOfCode

Online Java Tutorial - Cafe Au Lait

Text - Java Concepts by Cay Horstmann (Chapter 6 - Decisions) *We have six copies of this book in the computer lab*