Java do-while loop with Example

A programming language uses control statements to control the flow of execution of a program. In Java programming, we can control the flow of execution of a program based on some conditions. Java control statements can be put into the following three categories: selection, iteration, and jump. Java iteration statements allow program execution to repeat one or more statements. Java's iteration statements are while loop, do-while loop, and for loop. These statements are commonly called loops. A loop repeatedly executes the same set of instructions until a particular condition is true.




Java do-while loop:


As you saw in our previous tutorial if the conditional expression of a while loop is initially false, then the body of the loop will not be executed at all. However, sometimes we want to execute the body of a while loop at least once, even if the conditional expression is false to begin with. In other words, there are times when you would like to test the conditional expression at the end of the loop rather than at the beginning. Then we should go for a do-while loop in java. The do-while loop always executes its body at least once, because of the condition expression is at the bottom of the loop.


Syntax of Java do-while loop:


do{
// body of the loop.
}
while(condition);


Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates.



Flowchart of Java do-while loop:

Java do-while loop



Example of Java do-while loop:

Here is a do-while statement that prints the values from 1 to 10. See the example below.

class DoWhileLoop{
	public static void main(String args[]){
        System.out.println("The values from 1 to 10 is: ");
		int num = 1; // initialization.
		
		do{
			System.out.println(num);
			num++; // updation.
		}

		// condition checking.
		while(num <= 10);
	}
}



Output:
Java do-while loop



Java do-while loop with Example Java do-while loop with Example Reviewed by Prashant Srivastava on December 19, 2019 Rating: 5

No comments:

Powered by Blogger.