The while loop

The while loop is also an entry controlled loop, similar to for loop. While loop is commonly used where iteration is not fixed. Unlike for loop, while loop doesn’t allow you to declare and initialize a variable in the loop statement. You can only specify a boolean expression in the loop statement.

Syntax

while (<codition>) {
    // Loop body
}

Simple example

In this example, we are printing a number from 0 to 9 with prefix “Item”. So it will print something like – Item 0, Item 1, Item 2… Item 9

public class SimpleExample {
    
    public static void main(String[] args) {

        int i = 0;

        while(i < 10) {
            System.out.println("Item " + i);
            i++;
        }

    }

}

Points to note

  1. While loop is an entry controlled loop, means the condition is checked before entering into loop body.
  2. Condition is evaluated every time and if it evaluated as true then control enters into loop body.
  3. The loop terminates when the condition is evaluated as false.
  4. Every time we need to increase/decrease the value of the condition variable.

Flow diagram

Natural numbers example

This is an example program that demonstrates how to use while loop. In this program, we are printing all the natural numbers up to N.

Natural numbers are numbers that are common and clearly in nature. As such, it is a whole, nonnegative number.

import java.util.Scanner;

public class PrintNaturalNumbers {
    
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        // Take number from user
        System.out.print("Enter any number : ");
        int num = scanner.nextInt();

        System.out.println("\nNatural numbers from 1 to " + num);

        int i = 1;

        while (i <= num) {

            System.out.print(i + " ");
            i++;
        }

    }

}