Java – While Loop

A loop statement allows a programme to repeat a set of instructions under certain conditions. This allows a programmer to build programmes with fewer lines of code and improve the readability of the code. To meet looping requirements, Java includes the following types of loops:

  • while loop
  • do-while loop
  • for loop

The While Loop

A Java While Loop lets you repeat a sequence of statements as long as a certain condition is true. The Java While Loop may be thought of as a looped if statement.

Syntax

while (condition) {
  statements;
}

Flow Diagram:

 

Java While Loop

In the example below, the programme utilises a while loop to add all numbers from 1 to 5.

public class MyClass {
  public static void main(String[] args) {
    int i = 0;
    int sum = 0;
    while (i <= 5) {
      sum = sum + i;
      i++;
    }
    System.out.println(sum);  
  }
}

The output of the above code will be:

15

The Do-While Loop

The do-while loop is a version of the while loop in which statements are executed before the conditions are checked. As a result, the do-while loop runs each statement at least once.

Syntax

do {
  statements;
}
while (condition);

Flow Diagram:

The do-while loop in the example below executes the statements once even if the condition is not met.

public class MyClass {
  public static void main(String[] args) {
    int i = 10;
    int sum = 0;
    do{
        sum = sum + i;
        i = i+1;
    }
    while (i <= 5);
    System.out.println(sum);  
  }
}

The output of the above code will be:

Leave a Reply

Your email address will not be published. Required fields are marked *