While Loop in Java with examples

In this article, we will be taking a deep dive into the topic of while loop using Java programming language. As we move forward in this article, we will cover topics like the use of while loops and its syntax and get a better understanding of the while loop by looking at a schematic flowchart.

We will also be looking at some common examples of while loops using programs. The best results will come if you practice the codes shown in the article and also try some variations of the same codes to master the concept.

What is the use of a While loop in Java?

A while loop is a programming instruction that repeats a set of instructions as long as a condition is met. Once the boolean condition turns false, then the loop terminates, and the block of code is no longer performed.

You can think of a while loop as an If statement that repeats itself. While loops are often used in programming languages when the number of iterations is not known.

What is the Syntax of the Java while loop?

The syntax of the while loop is shown below:

While (condition)
{
<statements>
<updation expression>
}

Let us take a moment to understand the syntax of the while loop: The condition is the termination condition of the loop. This means that as long as the condition is true, The statements inside the loop are executed until the condition becomes false. When the condition becomes false, the loop terminates, and the set of instructions after the loop starts executing.

But how does the condition become false? Well, within the body of the loop, we will have an updation expression to change the parameters in the condition. With each iteration, the parameter changes, and the next time it enters the loop, it checks if the condition still holds true or not with the new value of the parameter.

Before we look at some example codes of the while loop, let’s perfectly understand the working of the while loop by looking at its flowchart:

while loop chart

Examples of While loop in Java

Now that we have established our basics, and know the working of the while loop perfectly, let us take a look at some common and simple codes that involve the while loop

1. Printing first n natural numbers

The below-shown code prints the first n numbers:

import java.util.Scanner;
public class FirstCode
{
    private static Scanner FC;
    public static void main(String[] args) 
    {
        int n, i = 1;
        FC = new Scanner(System.in);
        
        System.out.print("Enter the number of natural numbers you want to print: ");
        n = FC.nextInt();	
        
        while(i <= n)
        {
            System.out.print(i+ "  "); 
            i++;
        }	
    }
}

Output:

Enter the number of natural numbers you want to print: 7

1 2 3 4 5 6 7

In the code shown above, the condition in the while loop is that the value of “i” must always be less than the number specified by the user (n). Here, our updation expression is ”i++”, where we increment the variable and then check the condition after every iteration.

2. Sum of the first n natural numbers

import java.util.Scanner;

public class FirstCode
{
    private static Scanner FC;
    public static void main(String[] args) 
    {
        int n, i =1, sum = 0;
        FC = new Scanner(System.in);
        
        System.out.print("Enter the number until which you want to find the sum: ");
        n = FC.nextInt();	
        
        while(i <= n)
        {
             sum = sum + i;
             i++;
        }
        System.out.println("The sum is "+sum);
    }
}

Output:

Enter the number until which you want to find the sum: 10
The sum is 55

3. Infinite while loop

This is something that you typically want to avoid, the infinite while loop is a common problem programmers run into when the condition you have written in the while loop is wrong.

The reason a while loop goes into an infinite loop is that the loop never encounters a situation where it can terminate, and then we run into the issue of an infinite loop. The below code is an example of an infinite loop:

class FirstCode
{
    public static void main(String args[])
    {
         int i=5;
         while(i>=1)
         {
             System.out.println(i);
              i++;
         }
    }
}

In this example, the condition states that “i is greater than or equal to 1” Since we started out with 5, and we keep incrementing the value of ‘i’, the condition never becomes false. Hence, the put will be a never-ending screen of numbers!!

Differences between a while loop and a do-while loop?

Both of them sound very similar, right? Well, they are not; they are substantially different. Let us take a look at the difference between both of the loops.

WHILE LOOP DO-WHILE LOOP
The statement is executed only after the condition is checked. The statements are executed at least once, and then the condition is checked.
If the condition is false, the statements may not be executed at all. The statements will be executed at least once regardless of the condition.
while loop is entry controlled loop. do-while is exit controlled loop.
The variable in the condition is set before the loop is executed. A variable can be initialized either before or inside a loop.
SYNTAX:

while(condition)

   statements; 

}

SYNTAX:

Do

 { 

    statements;

 }

while(condition);

Conclusion

You have now learned and know everything you need to know to master while loops. We have discussed the use of the while loop its syntax with the help of a flowchart and a couple of programs to understand the while loop, including an infinite while loop.

Leave a Reply

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