Programming Loops


Topics:
For loops
While loops

Handouts
Loops Challenges

Lesson
Remind the students how during the last lesson, on if statements, the robot was only able to do something once. Wouldn.t it be nice if we could tell the robot to do the same thing repeatedly? Well we can by using for loops.

Here is a basic for loop program:
  import josx.platform.rcx.*;
/**
* This program plays a C note 5 times
**/

public class LoopExample {

     public static void main (String[] args0)
     throws Exception {
          int i = 0;     // counter variable
    
          // loops 5 times
          for (i=0; i < 5; i++) {
               Sound.playTone(262,40); // C note
               Thread.sleep(500);    
          }
     }
}


This program plays a C note 5 times using a for loop. For loops allow us to repeat the same code a certain number of times.

A for loop is writen like this:
  for( i = 0 ; i < n ; i++ ) {
     // my code here
}

And it will repeate the code inside it n times


The other type of loop is a while loop. While loops keep looping as long as something is true. Here is an example of a while loop using a touch sensor.
  while ( Sensor.S2.readBooleanValue() == false ) {
     Sound.playTone(349,40);   // F note
}


This program plays an F note as long as the touch sensor is NOT pushed in (Sensor.S2.readBooleanValue() == false) When the touch sensor is pressed in the Sensor reads true (true != false) and the program breaks out of the loop and continues on.