while

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