The while loop in Java allows a loop block to be executed an arbitrary number of times until a condition is met.
In java the “while loop” can be used in two different ways. The ways are “while-do” and “do-while”. According to your algorithm you can select and use one of them.
The “while-do” form, before executing the code block, allows the condition to be tested. It means that it is possible for the code block never to be executed. Firstly check the condition and then execute the code block.
Generally “while-do” syntax is:
while (condition) {
code_block;
}
In this syntax, “while-do” loop, it is important to know that, the keyword “do” is not used.
“do-while” loop does not check the condition until the loop code block is executed. It means that in a “do-while” loop the code block will be run at least once.
Generally “do-while” syntax is:
do {
code_block;
} while(condition)
The condition can be any expression that evaluates a Boolean value.
Now, by using “while-do” we write a code block which will output the number 1-10.
int i = 1
while (i < 11) {
System.out.println(i);
i = i + 1;
}
Output : 1 2 3 4 5 6 7 8 9 10
Now , by using “do-while” we write a code block which will output the numbers 1-10.
int i = 1
do {
System.out.println(i);
i = i + 1;
} while (i < 11)
Output : 1 2 3 4 5 6 7 8 9 10
No comments:
Post a Comment