Post

Loop Instructions

Loops allow a set of instructions to be executed repeatedly based on a condition.

Loop Instructions

Java has three main types of loops:

Loop TypeUse Case
forKnown number of repetitions
whileUnknown repetitions, check before each iteration
do-whileSimilar to while, but always runs at least once

1. For Loop

  • Syntax:
    1
    2
    3
    
    for (initialization; condition; update) {
      // code block
    }
    
  • Example:
    1
    2
    3
    
    for (int i = 1; i <= 5; i++) {
      System.out.println("Count: " + i);
    }
    
  • Flow:
    1. Initialize i = 1
    2. Check condition i <= 5
    3. Execute code
    4. Update i++
    5. Repeat step 2.

2. While Loop

  • Syntax:
    1
    2
    3
    
    while (condition) {
      // code block
    }
    
  • Example:
    1
    2
    3
    4
    5
    
    int i = 1;
    while (i <= 5) {
      System.out.println("Count: " + i);
      i++;
    }
    
  • Flow:
    1. Check condition.
    2. If true, run the block and repeat step 1.
    3. Else, end process.

3. Do-while Loop

  • Syntax:
    1
    2
    3
    
    do {
      // code block
    } while (condition);
    
  • Example:
    1
    2
    3
    4
    5
    
    int i = 1;
    do {
      System.out.println("Count: " + i);
      i++;
    } while (i <= 5);
    
  • Flow:
    1. Run the block once
    2. Check the condition.
    3. If true, run the block and repeat step 2.
    4. Else, end process.

4. Loop Control: break and continue

  • break: exit the loop early.
  • continue: skip the current iteration.

  • Example:
    1
    2
    3
    4
    5
    
    for (int i = 1; i <= 5; i++) {
      if (i == 3) continue;  // skip 3
      if (i == 5) break;     // stop at 4
      System.out.println(i);
    }
    

    Code Demo

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
    public class LoopExamples {
      public static void main(String[] args) {
          // for loop
          for (int i = 0; i < 3; i++) {
              System.out.println("for loop: " + i);
          }
    
          // while loop
          int j = 0;
          while (j < 3) {
              System.out.println("while loop: " + j);
              j++;
          }
    
          // do-while loop
          int k = 0;
          do {
              System.out.println("do-while loop: " + k);
              k++;
          } while (k < 3);
      }
    }
    

    Output:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    for loop: 0
    for loop: 1
    for loop: 2
    while loop: 0
    while loop: 1
    while loop: 2
    do-while loop: 0
    do-while loop: 1
    do-while loop: 2
    
This post is licensed under CC BY 4.0 by the author.