‹‹ Previous
Next ››
Java 'Do...While' Loop
- The 'do..while' loop is used for repeating a set of instructions.
- In 'do..while' loop testing condition is given in 'while' part of the 'do..while' loop.
- No testing is given in 'do' part of the loop.
- The 'do..while' executes instructions within the loop at least once, then after it checks the testing condition.
- If testing condition in 'while' part of the loop is true, then it executes the instructions again.
- If testing condition is false, then the loop terminates.
- Number of repetition is not fix in the 'do..while' loop. However, number of repetitions is fix in 'for' loop
- Number of repetitions depends on the condition which is used in the 'while' part of the loop.
- The 'do..while' loop is used when number of repetition is not known in advance and it depends on condition given in the 'while' part.
Example
Program: Display the message "Dear Learner", if user press 1. Otherwise, the 'while' loop terminates.
import java.util.*;
class DispMessg {
public static void main(String args[])
{
Scanner userinput = new Scanner(System.in);
int choice = 1;
do
{
System.out.println("Dear Learner");
System.out.println("Do you want to display the message more (Press 1) :");
choice = userinput.nextInt();
}while(choice == 1)
}
}
Explanation of the program
- In this program, Frequency of displaying the message "Dear Learner" depends on user input.
- if user gives input 1 then message "Dear Learner" will be displayed.
- if user gives input other than 1, then 'while' part of 'do..while' loop condition becomes false and the loop terminates.
Output of the program
Dear Learner
Do you want to display the message more (Press 1) :
1
Dear Learner
Do you want to display the message more (Press 1) :
1
Dear Learner
Do you want to display the message more (Press 1) :
1
Dear Learner
Do you want to display the message more (Press 1) :
1
Dear Learner
Do you want to display the message more (Press 1) :
1
Dear Learner
Do you want to display the message more (Press 1) :
0
‹‹ Previous
Next ››