while

Figure 159. A while loop Slide presentation
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!
A while loop

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 Slide presentation
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 Slide presentation
while (booleanExpression)
   (block | statement)

Figure 162. Empty while body Slide presentation
int threeSeries = 1;

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

System.out.println(threeSeries);

Exercise: Guess resulting output.


exercise No. 68

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);
}

exercise No. 69

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);
}