The Do-while Loop
It is also repetitive control structure and executes the body of the loop once irrespective of the condition, then it checks the condition and continues the execution until the condition becomes false.
Syntax:
do
{
. . . . . .
body of the loop;
. . . . . .
}
while(condition);
here the statements within the body the loop is executed once then it checks for the condition, if it is true, then it executes body until the condition becomes false.
Example:
do
{
n=n+1;
System.out.println(The N Value is : "+ n;
}
while(n<=15);
The do-while statement is a less commonly used loop construct in programming but does have its uses. For example, the do-while is convenient to use when the statements within the loop must be executed at least once.
Example:
public class doWhileDemo
{
public static void main(String args[])
{
int n=6;
System.out.println(“Initial Value of n is: “+n);
do
{
System.out.println(“Inside do-while loop”);
System.out.println(“Now the N value is : “+n);
--n;
}
while(n>1);
System.out.println(“The out of the do-while loop! “);
}
}
Output will be
Initial Value of n is: 6
Inside do-while loop
Now the N value is :6
Inside do-while loop
Now the N value is :5
Inside do-while loop
Now the N value is :4
Inside do-while loop
Now the N value is :3
Inside do-while loop
Now the N value is :2
The out of the do-while loop!
System.out.println(“The out of the do-while loop! “);
}
}
Output will be
Initial Value of n is: 6
Inside do-while loop
Now the N value is :6
Inside do-while loop
Now the N value is :5
Inside do-while loop
Now the N value is :4
Inside do-while loop
Now the N value is :3
Inside do-while loop
Now the N value is :2
The out of the do-while loop!
No comments:
Post a Comment