wiki:ControlSystems/SoftwareTeam/Training/GettingStarted/Loops

It's important for a program to be able to do things repeatedly; for example, a robot must read its sensors repeatedly and react only when certain conditions are met.

  1. Create a new project folder named LoopExample
  2. Open the LoopExample folder
  3. Create a new file (File->New File)
  4. Cut and paste the following program into the editor:
    public class LoopExample {
        public static void main(String args[]) {
            int counter;  
    
            counter = 1;
            while (counter <= 10) {
                System.out.println(counter);
                counter = counter + 1;
            }
        }
    }
    
  5. Save the program as LoopExample.java
  6. Run the program in the debugger with a breakpoint set at the line while (counter <= 10)
  7. Step through the program a line at a time, observing the program output, variables, and flow of execution

Understanding the program

Our program:

  1. Creates a loop counter variable
  2. Initializes the loop counter to 1
  3. Repeatedly evaluates the expression (counter <= 10) and while the expression evaluates as true
    1. prints the counter value
    2. increments the counter value by 1

The result of running the program is that the numbers 1 through 10 are printed. With only 10 iterations of the loop, you might ask whether it might be easier to just print each number manually, but consider a loop that might require thousands of iterations or that might run indefinitely until something happened:

    while (distanceToTarget > 0) {
       driveForward(0.50);
       distanceToTarget = checkDistance();
    }

Java includes three types of loop statements:

  • while
  • for
  • do

Extra credit

  • Read more about Java loops
  • Re-write the sample program using a do loop
  • Re-write the sample program using a for loop
Last modified 6 years ago Last modified on Nov 4, 2019, 3:37:07 PM