Do While Loop in Java

Do..While loop is used in iterating program where the condition is applied. In this page, you will learn the basics of Do?.While loop and how to use it with the help of an example.

Do While Loop in Java

Do..While loop is used in iterating program where the condition is applied. In this page, you will learn the basics of Do?.While loop and how to use it with the help of an example.

Do While Loop in Java


Do while loop in Java

There are three loops most commonly used in Java e.g. While loop, Do….While loop, and For loop. These loops are used in iterating statements in which there is a need to execute the program a least one time. Moreover, these loops are used to repeat the process until the condition met.

Do while loop is java is slightly different with While loop as in While loop statement the condition is first checked and if it is found true, the program executed otherwise the repetition continuous till the condition becomes true. On the contrary in Do…..While loop, the program first execute and then check the condition, if condition found ture, it executes and if not, the repetition continues, means the program executives in at least second time.

The Syntax for the do-while loop:

do
  {
  statements;
  }
  while(condition);

In this example you will see how to use the do-while loop statement. The values are already given the variable n and r in the program after that it calculate the program and print the results first the original number and later number in reverse order.

Here is the code of the program:-

public class DoWhile{
  public static void main(String[] args){
  int n = 12345;
  int t,r = 0;
  System.out.println("The original number : " + n);
  do{
  t = n % 10;
  r = r * 10 + t;
  n = n / 10;
  }while (n > 0);
  System.out.println("The reverse number : " + r);
  }
}