...

/

while & do-while Loops

while & do-while Loops

In this lesson, an introduction of the while and do-while loops in Java is provided. It uses coding examples to show their implementation and explain their workings.

Loops allow a programmer to execute the same block of code repeatedly.

The while loop

The while loop is really the only necessary repetition construct. It will keep running the statements inside its body until some condition is met.

The syntax is as follows:

Press + to interact
while ( condition ) {
//body
}

The curly braces surrounding the body of the while loop indicate that multiple statements will be executed as part of this loop.

Here’s a look at the while loop code:

Press + to interact
class HelloWorld {
public static void main(String args[]) {
int x = 0;
int y = 0;
while (x != 4) { // the while loop will run as long as x==4 condition is being met
y += x;
x += 1;
}
System.out.println("Value of y = " + y);
System.out.println("Value of x = " + x);
}
}

Below is an illustration of the code above to ...