4.1 While Loops

While loops run until the given condition is false. Format of loop below.

int index = 0; // iterating value
while (index < 5) { // condition, if this is false, the loop terminates
    System.out.println(index); // body code
    index++; // iterates the iterating value
}
0
1
2
3
4
# Python Version
i=0
while (i<5):
    print(i)
    i+=1
0
1
2
3
4

Explanation

  • in the above while loop:
    • index is the incrementing variable
    • index < 5 is the condition (once index < 5 is false, this loop breaks)
    • System.out.println(i); is the body code that runs every time the loop iterates
    • index++; is incrementing the incrementing variable

Do While Loops:

  • This type of while loop runs the block inside the do{} statement once, then iterates through the loop
  • this ensures that the code runs at least once

Example of Do While loop below

int i = 0; // iterating value
do { // this makes sure the code runs at least once
    System.out.println(i); // body code
    i++; // iterates the iterating value
} while (i < 5); // condition, if this is false, loop terminates
0
1
2
3
4

Explanation:

  • in the above loop:
    • code inside of the do{} statement runs at least once, then keeps on running as long as the condition, i<5, is true.
    • similarly to the normal while loop, there is body code, and there is an incrementing variable

IMPORTANT:

  • While loops to not have to have an incrementing variable, for example, you can have a loop that iterates as long as there are items present in a list
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);

System.out.println(list + " before loop!!");
while (!list.isEmpty()) {
    System.out.println("Element: " + list.remove(0));
}
System.out.println(list + " after loop!!");
[10, 20, 30, 40] before loop!!
Element: 10
Element: 20
Element: 30
Element: 40
[] after loop!!

Fun While Loop Hack:

  • find and fix the missing increment in the while loop
int i = 0;
while (i < 5) {
    System.out.println(i);
}
2
15


Iteration: 0

Current Velocity: 2, 2