Java do while Loop with Examples

This article will explore the do-while loop in the Java programming language in depth. As we progress, we will discuss topics such as the use of do-while loops and their syntax and gain a better understanding of the do-while loop by looking at a schematic flowchart.

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

What is the use of a Do While loop?

A do-while loop is a programming statement that repeats a code block once a condition is met. The condition is checked at the end of the loop, so the code inside the loop will always be executed at least once. Do-while loops are often used when the number of times the loop should run is unknown.

Differences between Java while loop and do while loop

While loops and do-while loops sound similar, they are not. In a while loop, the condition is checked first, and only if it is true are the statements executed. The statements are executed first in a do-while loop, and then the condition is checked.

A do-while loop will consistently execute at least once, even if the condition is false because the condition is checked at the end of the loop. In a while loop, the condition is checked at the beginning, so the statements inside the loop may not execute if the condition is false.

Here is a list of the differences between the two 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);

Syntax of Java do while loop

The syntax of the do-while loop is shown below:

do
{
    <Statments>
<Updation expression>
}
while (condition);

Let us take a moment to understand the syntax of the do-while loop: Firstly, we have two blocks, the do block and then the whole block. First, the body of the loop, along with the updation expression, is written in the do block. Once this part is executed, the condition is checked from the whole block.

If the condition is false, the loop will terminate. If it is true, the loop will go back to the do block and execute the body of the loop again, until the condition becomes false.

The body of the loop contains 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 examples codes of the while loop, let’s master the working of the while loop by looking at its flowchart:

DO WHILE LOOP chart

Examples of Java Do While loop

Now that we have a good understanding of the basics and how the do-while loop works, let’s look at some common and simple codes that use 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)
        do 
        {
            System.out.print(i+ "  "); 
            i++;
        }
        while(i <= n);
    }
}

Output:

Enter the number of natural numbers you want to print: 5
1 2 3 4 5

In this example, we first print the first number (variable i), and then after incrementing the value, we check if it satisfies the condition. In this example, the 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();	
        
        do
        {
             sum = sum + i;
             i++;
        }
        while(i <= n);
        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

An infinite while loop is a common problem that programmers encounter when the condition in the loop is incorrect. It is something that you should typically avoid.

A while loop goes into an infinite loop because the condition is always true, so the loop keeps running as the condition never becomes false.

The code below is an example of an infinite loop:

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

In this example, the condition “i is greater than or equal to 1” is always true because i starts at 5 and is incremented each time through the loop. This means that the loop will never end, and the output will be a never-ending screen of numbers.

Conclusion

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

Leave a Reply

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