The while statement provides an alternate way of repeatedly executing a block of statements. It is frequently used when the number of times the block is to be executed is not known. Its general form consists of the while
keyword followed by a set of parentheses enclosing a logical expression and then a statement. The body of the loop will execute as long as the logical expression evaluates to true:
while (<boolean-expression>) <statements>;
A simple example duplicates the first for loop example where we display the numbers 1 to 10 on a single line:
int i = 1;
while(i <= 10) {
System.out.print(i++ + " ");
}
System.out.println();
The output is as follows:
1 2 3 4 5 6 7 8 9 10
The following example is a bit more complicated and computes the factors of the number
variable:
int number; int divisor = 1; Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); number = scanner.nextInt(); while (number >= divisor) { if ((number % divisor...