Java do-while Loop

In our previous articles about Java while loop and Java forloop, we concluded that loops are the best choice for executing repetitive tasks efficiently. Among the various loop structures, the Java do-while loop offers a unique and powerful mechanism for iterative execution. 

Unlike other loops, the do-while loop guarantees that the code block is executed at least once before evaluating the loop condition. In this detailed article, we will explore the essentials of the Java do-while loop, discuss its syntax and behavior, and provide many examples along with their corresponding outputs in order to make the concept clear about Java do while loop.

 

Understanding the Java do-while Loop:

The do-while loop in Java is a control flow statement that iteratively executes a block of code based on a specified condition. Unlike the while loop, which evaluates the condition before entering the loop, the do-while loop executes the code block first and then checks the condition. This ensures that the code block is executed at least once, regardless of the condition's initial evaluation.

 

Syntax of the do-while Loop:

The syntax of the do-while loop consists of the keyword "do," followed by the code block enclosed within curly braces, and concluded with the "while" keyword followed by a Boolean expression and a semicolon.

Syntax:

do{  

    //code to be executed  

} while(condition);  

 

Java do while loop Example1:

int count = 1;

do {

   System.out.println("Count: " + count);

   count++;

} while (count <= 5);

 

Output:

Count: 1

Count: 2

Count: 3

Count: 4

Count: 5

```

 

 Working Principle of the do-while Loop:

1. Code block execution: The code block within the do-while loop is executed first, regardless of the condition's initial evaluation.

2. Condition evaluation: After executing the code block, the loop condition is evaluated. If the condition evaluates to true, the loop continues, and the code block is executed again. If the condition evaluates to false, the loop is terminated, and control is passed to the next statement after the loop.


Java do while loop

Working of do-while loop


Practical Use Cases and Examples of Java do while loop:

 

1. User Input Validation:

import java.util.Scanner;

 

int input;

do {

   Scanner scanner = new Scanner(System.in);

   System.out.print("Enter a positive number: ");

   input = scanner.nextInt();

} while (input <= 0);

 

System.out.println("You entered: " + input);

 

Output:

Enter a positive number: -6

Enter a positive number: -3

Enter a positive number: 7

You entered: 7

 

Explanation:

In the above example, first body of loop will be executed to get number from user, then condition will be checked, if the input is greater than 0, loop will get terminated else it will keep executing loop body and checking condition until user enters a number greater than 0.

 

2. Rolling a Dice Until a Specific Number is Rolled:

 

import java.util.Random;

 

int dice;

Random random = new Random();

 

do {

   dice = random.nextInt(6) + 1;

   System.out.println("Rolled: " + dice);

} while (dice != 6);

 

Explanation:

we are using the Java Random class from the java.util package to simulate rolling a dice until we get a value of 6.

First, we create an instance of the Random class by initializing Random random = new Random();. This allows us to generate random numbers.

The statement dice = random.nextInt(6) + 1; generates a random integer between 0 and 5 using nextInt(6). By adding 1 to the result, we ensure that the value of dice falls within the range of 1 to 6, simulating the roll of a standard six-sided dice.

The loop continues to execute until the condition dice != 6 is satisfied. Once we roll a 6, the condition evaluates to false, and the loop terminates.

3. Finding factorial of a number:

Write a program to find the factorial of a number entered by the user using a while loop.

import java.util.Scanner;

public class Factorial {

    public static void main(String[] args) {

        int number;

        System.out.println("Enter the number: ");

        Scanner scanner = new Scanner(System.in);

        number = scanner.nextInt();

        scanner.close();

        long fact = 1;

        int i = 1;

        while(i<=number){

            fact = fact * i;

            i++;

        }

        System.out.println("Factorial of "+number+" is: "+fact);

    }

}

 

When you run the program, you will get similar output like this:

Enter the number: 6

Factorial of 6 is: 720

4. Finding Fibonacci series:

Write a program to display the Fibonacci series based on the user input. For example, if the user enter 5, the program will print 0, 1, 1, 2, 3

import java.util.Scanner;

public class FibonaciiSeries {

 

    public static void main(String[] args) {

 

        int count, num1 = 0, num2 = 1;

        System.out.println("How may numbers you want in the sequence:");

        Scanner scanner = new Scanner(System.in);

        count = scanner.nextInt();

        System.out.print("Fibonacci Series of "+count+" numbers:");

 

        int i=1;

        while(i<=count)

        {

            System.out.print(num1+" ");

            int sumOfPrevTwo = num1 + num2;

            num1 = num2;

            num2 = sumOfPrevTwo;

            i++;

        }

    }

}

 

When you run the program, you will get similar output like this:

How may numbers you want in the sequence: 6

Fibonacci Series of 6 numbers:0 1 1 2 3 5

 

Key Differences Between do-while and Other Loops:

·        The do-while loop always executes the code block at least once, regardless of the condition's initial evaluation.

·        The while and for loops, in contrast, evaluate the condition before entering the loop, potentially skipping the execution of the code block entirely.

 

The Java do-while loop provides an amazing way to handle iterative tasks, ensuring that the code block is executed at least once. By understanding its syntax, working principle, and practical applications, you can use the power of the do-while loop to solve various programming challenges.

Through the provided examples and their outputs, you can examine firsthand how the do-while loop facilitates  you to iterate dynamically and control the flow of your Java programs. 

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !