Do-While loop in Java

Do-While loop in Java
Do-While loop in Java 1

most of the programmers don’t use a do-while loop. In the do-while loop, the loop condition is tested at the end of the loop, so at least the loop is executed for one time.

syntax

do
 {
 statements;
 }
 while (testExpression);

flowchart

Do-While loop in Java 2

example

import java.util.*;
class dowhile
{
         public static void main(String args[])
         {
            Scanner s=new Scanner(System.in);
            System.out.printf("Enter range number");
            int n1=s.nextInt();
            int x=0,sum=0;
            do
            {
    
             sum += x;
             x++;
             }
            while(x<=n1);
            System.out.println(sum);
           
            s.close();
          }
}

output

Enter range number 50
1275

here, from the example given above. the do is executed once without any condition.then do looks for while for the condition, if the condition is true, the loop will be executed again and again until the test condition(while) becomes false.this do-while loop is useful in the programmes like the loop should be executed at least once .

Default image
Vishal Devxo
Vishal is a DevOps engineer and a Backend developer, he spends all his time for creating good tutorials with better visuals and blogging, developed some projects based on Python-Django, some hacking modules and scripts in python
Leave a Reply