Java: Do-While Loop

do-while loop

Do While Loop In Java

Looping is a cardinal feature of any programming language. We will be learning about Do While Loop In Java programming language.

Using loops saves the programmer from the hassle of writing the same code again and again to obtain the desired results. We have three different loops in programming:

  • For Loop.
  • While Loop.
  • Do- While loop.

Understanding the Concept

A do-while loop is a functionality that is similar to the standard while loop except the fact that in this type of looping technique the body of the loop will be executed at least once, even if the condition check returns false.. Also, a do-while loop evaluates the condition at the end of the loop.

It is also known as Post-tested loop. The steps in this looping technique are:

  • The control flow first enters the loop.
  • The body of the loop is executed initially.
  • Now, the condition specified is evaluated.
    • If it returns true, the body of the loop is executed again.
    • If it returns false, the control flow falls out of the loop
Do while loop

Syntax

do
{
    // loop body
    
    update_count
}
while (condition_check);

Now that we have seen the syntax of the do-while loop, let us understand how it works via an example. 

Suppose we want to print a table of 4 up till 10. Instead of writing the code again and again we can use the do while loop as follows:

Run

public class Main 
{ 
    public static void main(String args[]) 
    { 
        int i = 1; 
        do {

             System.out.println(i*4);

               i++;
           }

         while (i < 11);
    }
}

Output

4
8
12
16
20
24
28
32
36
40

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription