prev | TOC | next

Flow Control

files: LoopingLines.java, IsItEven.java, IsItEvenOrOdd.java (help)


Programs are much more than the simple sequential execution of statements.  We often need to excute a section of code repeatedly, perhaps with a change of some of the program's state each time.  We also commonly need to execute different sections of code depending upon whether some condition is true of false.  This lesson will discuss these two types or flow control that are commonly seen in programs: Looping and Branching.

Looping

Suppose you want to draw 3 vertical lines on the display. One way of doing this would be:

penUp();
setPos(200, 100);
penDown();
setPos(200, 200);

penUp();
setPos(220, 100);
penDown();
setPos(220, 200);

penUp();
setPos(240, 100);
penDown();
setPos(240, 200);

hideTurtle();

This certainly works, but it is duplicating what is basically the same code three times. What would happen if you wanted to draw 20 lines, or 100?

While loops

A better way of handling this would be to use a while loop. It's basic form is:


while (some expression is true)
{
    do something;
}


To use a while loop to solve our problem, we could rewrite the above code as:

int x = 200;
int count = 0;
while ( count < 3 )
{
    penUp();
    setPosition( x, 100 );
    penDown();
    setPosition( x, 200 );
    x = x + 20;
    count = count + 1;
}
hideTurtle;

Comparing the two pieces of code, the while loop may not seem that much simpler.  But imagine the benefits when drawing 10 lines instead of 3. The code without the while loop would be quite long. However, with the while loop we only need to change the "3" to a "10."

In the above case, we first define an int variable x to hold the x-coordinate of the line being drawn. We also define the variable count which keeps track of how many times we have executed the loop.  Then we get to the while statement itself.  The while statement will be repeated as long as the expression in parentheses is true (in this case, count < 3).  

The body of the while loop is the code block between "{" and "}".  This block is similar to one piece of the un-looped version, except we use the variable x to determine the x-coordinate of each line.  This x-coordinate is increased by 20 each time through the loop.  The last statement of the body increments count, to indicate that we have executed the loop one more time.  An common error is to forget to increment count, causing the loop to repeat forever.

The LoopingLines turtle in the folder that was loaded with this lesson has the above code that you can experiment with.

For loops

for loop does basically the same thing as a while loop.  In fact, you could get by never using a for loop and sticking to while loops entirely.  However, the for loop is a more compact and readable construct and it is often preferred for that reason.  You can chose to use whichever form is most clear to you.

The basic form of a for loop is:

for (initialize variables; test for continuation; increment variables)
{
    do something;
}

To use a for loop to solve our problem, we would write something like:

int x = 200;
for (int count = 0; count < 3; count++)
{
   penUp();
   setPosition(x, 100);
   penDown();
   setPosition(x, 200);
   x = x + 20;
}
hideTurtle();


Notice how the initializing, termination testing, and variable incrementing is all compressed into one compact statement.  We can now easily change how many lines are drawn by modifying the "3" in the second line to something else.

Branching

Often you want to execute different pieces of code depending on some condition within the program.  Java has several constructs for doing this.  We will look at two: the if statement and the if/else statement.

if statement

The basic form of the if statement is:

if (some expression is true)
{
    do something;
}

For example suppose you wanted to test whether a number the user typed in was even.  To do so you would:

  • print out a prompt for the user to type a number
  • read in the number
  • test if it was even
  • write out a message if it was

The turtle IsItEven in this lesson's folder does just this.  Here is the relevant code:

1.  public void runTurtle()
2.  {
3.      Console.print( "Type an integer number > " );
4.      int input = Console.readInt();
5.          
6.      if ( input % 2 == 0 )
7.          Console.println( input + " is even." );
8.  }

  • Line 3 prints the prompt for the user to type a number. 
  • Line 4 declares an int variable called input, reads the integer the user typed and stores it in the variable. 
  • Line 6 uses the if statement to test whether the value input is even.  If so the statement following on line 7 is executed and a message is printed that it's even.

On line 6, the test for evenness is performed using the "remainder" operator.  Recall the input % 2 yields the remainder when input is divided by 2.  If this remainder is equal to 0 then the number is even.

The statement immediately following the if statement is executed when the condition is true.  This may be a single line statement such as line 7, or it could be a code block that takes the place of a single statement.

if/else statement

The if/else statement is almost identical to the if statement, except it specifies an alternate piece of code to execute when the condition is false.

if (some expression is true)
{
    do something;
}
else
{
   
do something else;
}

The else clause of the if statement must follow immediately after the statement (or code block) that is executed when the condition is true.  You cannot have an else clause without the proceeding if part.

See the IsItEvenOrOdd turtle for an example of the use of the if/else clause.

Exercises

Make a copy of the LoopingLines turtle (using the Import file command) and call it FancyLoopingLines.  Modify the code so that every other line is drawn red rather than black.