This loop can be used for executing the statements multiple times. A do-while loop has to be used when we do not know the exact number of iterations.
Syntax:
do{
statements;
}
while(condition);
Program 8:
class DoWhileDemo{
public static void main(String args[]){
int n=9,i=1;
do{
System.out.println(n+"*"+i+=+(n*i)));
i++;
} while (i<=10);
}
}
Rule1: Specifying a condition to do-while loop is mandatory and it should be of boolean type.
Rule2: Specifying the { } is optional. If we do not specify the { } then we must specify exactly only one statement. If we want to consider multiple statements then specifying the { } is mandatory. Within the { } we can specify any number of statements.
Difference between while loop & do-while loop
- In a while loop the statements will execute after evaluating the condition, whether in a do-while loop the statements will exexute before evaluating the condition.
- In a while loop if the condition is false for the first time then the statement will not execute, whereas in a do-while loop if the first time then the statements will execute for one time.
- In a while loop the statements will execute for 0 or more times, whereas in a do-while loop the statements will execute for 1 or more times.