Changes between Initial Version and Version 1 of ControlSystems/SoftwareTeam/Training/GettingStarted/Loops


Ignore:
Timestamp:
Nov 4, 2019, 3:37:07 PM (6 years ago)
Author:
David Albert
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • ControlSystems/SoftwareTeam/Training/GettingStarted/Loops

    v1 v1  
     1It'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
     31. Create a new project folder named !LoopExample
     41. Open the !LoopExample folder
     51. Create a new file (File->New File)
     61. Cut and paste the following program into the editor:
     7{{{
     8public 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}}}
     201. Save the program as !LoopExample.java
     211. Run the program in the debugger with a breakpoint set at the line while (counter <= 10)
     221. Step through the program a line at a time, observing the program output, variables, and flow of execution
     23
     24=== Understanding the program
     25Our program:
     261. Creates a loop counter variable
     271. Initializes the loop counter to 1
     281. 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
     32The result of running the program is that the numbers 1 through 10 are printed.
     33With only 10 iterations of the loop, you might ask whether it might be easier to just print each number manually,
     34but 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
     42Java 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