| 1 | 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. |
| 2 | |
| 3 | 1. Create a new project folder named !LoopExample |
| 4 | 1. Open the !LoopExample folder |
| 5 | 1. Create a new file (File->New File) |
| 6 | 1. Cut and paste the following program into the editor: |
| 7 | {{{ |
| 8 | public class LoopExample { |
| 9 | public static void main(String args[]) { |
| 10 | int counter; |
| 11 | |
| 12 | counter = 1; |
| 13 | while (counter <= 10) { |
| 14 | System.out.println(counter); |
| 15 | counter = counter + 1; |
| 16 | } |
| 17 | } |
| 18 | } |
| 19 | }}} |
| 20 | 1. Save the program as !LoopExample.java |
| 21 | 1. Run the program in the debugger with a breakpoint set at the line while (counter <= 10) |
| 22 | 1. Step through the program a line at a time, observing the program output, variables, and flow of execution |
| 23 | |
| 24 | === Understanding the program |
| 25 | Our program: |
| 26 | 1. Creates a loop counter variable |
| 27 | 1. Initializes the loop counter to 1 |
| 28 | 1. Repeatedly evaluates the expression (counter <= 10) and while the expression evaluates as true |
| 29 | 1. prints the counter value |
| 30 | 1. increments the counter value by 1 |
| 31 | |
| 32 | The result of running the program is that the numbers 1 through 10 are printed. |
| 33 | With only 10 iterations of the loop, you might ask whether it might be easier to just print each number manually, |
| 34 | but consider a loop that might require thousands of iterations or that might run indefinitely until something happened: |
| 35 | {{{ |
| 36 | while (distanceToTarget > 0) { |
| 37 | driveForward(0.50); |
| 38 | distanceToTarget = checkDistance(); |
| 39 | } |
| 40 | }}} |
| 41 | |
| 42 | Java includes three types of loop statements: |
| 43 | * while |
| 44 | * for |
| 45 | * do |
| 46 | |
| 47 | === Extra credit |
| 48 | * Read more about [https://www.geeksforgeeks.org/loops-in-java/ Java loops] |
| 49 | * Re-write the sample program using a '''do''' loop |
| 50 | * Re-write the sample program using a '''for''' loop |