### while

Figure 159. A while loop
 final int repetitions = scan.nextInt(); ❶ int loopCount = 0; ❷ while (loopCount < repetitions ❸) { System.out.println("Do not copy!"); ❹ loopCount++; ❺ }Do not copy! Do not copy! Do not copy! The code block will be repeated this number of times. Helper variable keeping track of repetitions. Condition to be checked prior each execution. Code block of statement(s) to be repeated. Helper variable being incremented during each iteration.

Figure 160. Combining increment and termination condition
Code Execution
System.out.print("Enter repetitions: ");
final int repetitions = scan.nextInt();
int loopCounter = 0;

while (loopCounter++ < repetitions) {
System.out.println("Do not copy!");
}
Enter repetitions: 3
Do not copy!
Do not copy!
Do not copy!

Figure 161. while syntax
while (booleanExpression)
(block | statement)

Figure 162. Empty while body
int threeSeries = 1;

while ((threeSeries *=3 ) < 100);

System.out.println(threeSeries);

Exercise: Guess resulting output. No. 67

#### Generating square numbers

 Q: Write an application printing the first ten square numbers. The output should look like: The square of 1 is 1 The square of 2 is 4 The square of 3 is 9 The square of 4 is 16 The square of 5 is 25 The square of 6 is 36 The square of 7 is 49 The square of 8 is 64 The square of 9 is 81 The square of 10 is 100 A: int counter = 0; while (counter++ < 10) { System.out.println("The square of " + counter + " is " + counter * counter); } No. 68

#### Calculating factorial

 Q: The factorial $n !$ of a given integer n is being defined as the following product: $n ! = n × ( n - 1 ) × ⋯ × 2 × 1$ In addition the factorial of zero is being defined as: $0 ! = 1$ Write an application asking a user for an integer value and calculate the corresponding factorial e.g.: Enter an integer value: 5 5! == 120 A: public static void main(String[] args) { final Scanner scan = new Scanner(System.in)); System.out.print("Enter an integer value: "); final int value = scan.nextInt(); long factorial = 1; int i = 1; while (i++ < value) { factorial *= i; } System.out.println(value + "! == " + factorial); }