Loops

For loops allow a code to be repeated until a certain parameter is no longer true. There is then also nested loops where there will be a loop within a loop. And finally, a while loop will run through certain code as long as a certain condition is true.

for (int i = 0; i < 5; i++) {
    System.out.println(i);
  }
0
1
2
3
4
// Outer loop
for (int i = 1; i <= 2; i++) {
    System.out.println("Outer: " + i); // Executes 2 times
    
    // Inner loop
    for (int j = 1; j <= 3; j++) {
      System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)
    }
  }
Outer: 1
 Inner: 1
 Inner: 2
 Inner: 3
Outer: 2
 Inner: 1
 Inner: 2
 Inner: 3
int i = 0;
while (i < 5) {
  System.out.println(i);
  i++;
}
0
1
2
3
4

Homework

Homework