While Loop and Do While loop in Java

Loops: Loops help to execute the set of code blocks repeatedly many times till the condition is met.

Why do we need loops?

Let’s say we want to add 2 numbers which can be easily done by number1+number2

But what if there is a requirement to add 100 numbers? Well, here loops play an important role

As mentioned in the definition, the code block in the loop will run 100 times hence we’ll get the desired output, So loops are very efficient to execute the same instructions again and again.

Java Programming language has different types of loops:

  1. For loop
  2. While loop
  3. Do while loop

In this, we will learn about the while loop and Do while loop.

While loop:

While loop executes a code block as far as the condition specified is true.


How while loop works:

  1. The while loop evaluates the condition which is inside the parentheses after the “while” keyword
  2. If the condition is found to be true it will execute the block of code inside the loop
  3. Step 2 will occur again and again till the condition is false
  4. If the condition is false control will come out of the loop.

Refer to the flowchart for a better understanding

Flow chart:

Let’s see an example of how the while loop works internally:

Printing numbers from n to 1

Note: What if there is no “n- -” statement?

If there is no decrementation of n, then the while loop will execute an infinite number of times because the condition (base case to terminate loop) will never get false.

Program to print numbers from 1 to 10 in reverse order using while loop


Java Code

public class TUF {
  public static void main(String[] args) {

    int n = 10;
    while (n > 0) {
      System.out.print(n + " ");
      n--; //decrementing n by 1 

Output: 10 9 8 7 6 5 4 3 2 1

Do while loop:

Do while loop is also similar to the while loop, Do while loop also executes the statements inside the loop repeatedly till the condition turns out to be false, but the only difference is Do while loop executes the code first and then checks for the condition.


Flow chart:


Java Code

public class TUF {
    public static void main(String[] args) {

        int n = 1;
        do {
        }while (n<3);




First, the statements present in do will be executed without checking for condition, with n = 1, so 1 will be printed and n is incremented by 1 now n is 2

After 1st iteration the condition will be checked with the current value of n, the condition turns out to be true (2<3), again do will be executed and 2 is printed and n is incremented (n=3), 

Now the condition is false(3<3) so, the loop will be terminated.

Special thanks to Sai bargav Nellepalli for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article