Loops in Java
Looping is a common programming situation that you can expect
to encounter rather
regularly. Loop can simply be described as a situation in which you may need to execute
the same block of code over and over. Java supports
three looping constructs, which are as
follows:
for Loop
do…while Loop
while Loop
In
addition to this, the foreach looping construct also exists. However, this construct will
be explained in the chapter on arrays.
The while Loop:
A while loop is a control structure that permits you to rehash
an errand a specific number
of times. The syntax for this construct is as follows:
while(boolean_expression) {
/Statements
}
At the point when executing, if the boolean_expression
result is genuine, then the
activities inside the circle will be executed. This will proceed till
the time the result for the
condition is genuine. Here, key purpose of the while loop is that the circle may not ever
run. At the point when the interpretation is tried
and the result is false, the body of the
loop will be skipped and the first proclamation after the while circle will be executed.
Sample:
public class myTest {
public static void main(string args[]) {
int i=5;
while(i<10) {
System.out.print(” i = ” + i );
i++;
System.out.print(“\n”);
}
}
This would deliver the accompanying result:
x = 5
x = 6
x = 7
x = 8
x = 9
x = 5
Do'stlaringiz bilan baham: