Java Lab Documentation

while Loops

Category:Control Structures

A while loop is commonly used to execute a block of code while a condition is true.

  • a while loop evaluates the condition inside the parentheses

  • if the condition is true, the body of the loop will execute

  • the body will be executed until the condition evaluates to false

Examples

Print Numbers in a Pre-Defined Range

int i = 0;
int n = 4;

while(i < n) {
   System.out.println(i);
   i++;
}

Output:

0

1

2

3

Syntax

while (condition) {
   // code to execute
}