# Java Programming Tutorial

## Yet Another Exercises on Java Basics

These exercises are meant for submission to my online submission system.

### Getting Started Exercises

Write a program called `Add2Integers` that prompts user to enter two integers. The program shall read the two integers as type `int`; compute their sum; and print the result.

##### Test Cases
No. Sample Input Sample Output
`1`
`58`
`Enter first integer: Enter second integer: The sum is: 13`
`2`
`-5-8`
`Enter first integer: Enter second integer: The sum is: -13`
`3`
`8-8`
`Enter first integer: Enter second integer: The sum is: 0`
`4`
`80`
`Enter first integer: Enter second integer: The sum is: 8`
`5`
`-80`
`Enter first integer: Enter second integer: The sum is: -8`
`6`
`00`
`Enter first integer: Enter second integer: The sum is: 0`
##### Hints
```import java.util.Scanner;   // For keyboard input
/**
* 1. Prompt user for 2 integers
* 2. Read inputs as "int"
* 3. Compute their sum
* 4. Display the result
*/
public static void main (String[] args) {
// Declare variables
int number1, number2, sum;
Scanner in = new Scanner(System.in);  // Scan the keyboard for input

// Put up prompting messages and read inputs as "int"
System.out.print("Enter first integer: ");  // No newline for prompting message
number1 = in.nextInt();                     // Read next input as "int"
System.out.print("Enter second integer: ");
number2 = in.nextInt();

// Compute sum
sum = number1 + number2;

// Display result
System.out.println("The sum is: " + sum);   // Print with newline
in.close();  // Close Scanner
}
}```

#### Odd or Even (OddEven.java) (if-else and modulus)

Write a program called `OddEven` that prompts user for an integer. The program shall read the input as an `int`; and check if the integer is odd or even.

##### Test Cases
No. Sample Input Sample Output
`1`
`99 `
`Enter an integer:  99 is odd bye `
`2`
`88 `
`Enter an integer:  88 is even bye `
`3`
`0 `
`Enter an integer:  0 is even bye `
`4`
`-1 `
`Enter an integer:  -1 is odd bye `
`5`
`-4 `
`Enter an integer:  -4 is even bye `
##### Hints:
```      // Declare variables
int numberIn;   // input integer
......
// Prompt and read input as "int"
......

// Check odd/even and print result
// Use % to find the remainder dividing by 2, and compare with 0
if (numberIn % 2 == 0) {      // double-equal for comparison
System.out.println(......);
} else {
System.out.println(......);
}```

#### Multiple (Multiple.java) (if-else and modulus)

Write a program called `Multiple` that prompts user for 2 integers. The program shall read the inputs as `int`; and check if the first integer is a multiple of the second integer.

##### Test Cases
No. Sample Input Sample Output
`1`
`9911`
`Enter 1st integer: Enter 2nd integer: 99 IS a multiple of 11`
`2`
`9912`
`Enter 1st integer: Enter 2nd integer: 99 IS NOT a multiple of 12`
`3`
`510`
`Enter 1st integer: Enter 2nd integer: 5 IS NOT a multiple of 10`
##### Hints
1. Use two `int` variables: `number1` and `number2` to store the inputs.
2. Use modulus operator `%` to find the remainder and compare with zero, i.e., `if (number1 % number2 == 0) ...`. Take note that comparison operator is double-equal.

#### Arithmetic and Min/Max of 3 integers (SumProductMinMax3.java) (if-else and min/max)

Write a program called `SumProductMinMax3` that prompts user for three integers. The program shall read the inputs as `int`; compute the sum, product, minimum and maximum of the three integers; and print the results.

##### Test Cases
No. Sample Input Sample Output
`1`
`328`
`Enter 1st integer: Enter 2nd integer: Enter 3rd integer: The sum is: 13The product is: 48The min is: 2The max is: 8`
`2`
`442299`
`Enter 1st integer: Enter 2nd integer: Enter 3rd integer: The sum is: 165The product is: 95832The min is: 22The max is: 99`
`3`
`199-1990`
`Enter 1st integer: Enter 2nd integer: Enter 3rd integer: The sum is: 0The product is: 0The min is: -199The max is: 199`
##### Hints
```      // Declare variables
int number1, number2, number3;  // The 3 input integers
int sum, product, min, max;     // To compute these
Scanner in = new Scanner(System.in);  // Scan the keyboard

// Prompt and Read inputs as "int"
......

// Compute sum and product
sum = ......
product = ......

// Compute min
// The "coding pattern" for computing min is:
// 1. Set min to the first item
// 2. Compare current min with the second item and update min if second item is smaller
// 3. Continue for the next item
min = number1;        // Assume min is the 1st item
if (number2 < min) {  // Check if the 2nd item is smaller than current min
min = number2;     // Update min if so
}
if (number3 < min) {  // Continue for the next item
min = number3;
}

// Compute max - similar to min
......

// Print results
......```

#### Arithmetic and Min/Max of 5 integers (SumProductMinMax5.java) (if-else and min/max)

Write a program called `SumProductMinMax5` that prompts user for five integers. The program shall read the inputs as `int`; compute the sum, product, minimum and maximum of the five integers; and print the results.

##### Test Cases
No. Sample Input Sample Output
`1`
`51243`
`Enter 1st integer: Enter 2nd integer: Enter 3rd integer: Enter 4th integer: Enter 5th integer: The sum is: 15The product is: 120The min is: 1The max is: 5`
`2`
`-999998810`
`Enter 1st integer: Enter 2nd integer: Enter 3rd integer: Enter 4th integer: Enter 5th integer: The sum is: -811The product is: 0The min is: -999The max is: 99`
##### Hints

See previous question. Use five `int` variables: `number1`, `number2`, ..., `number5` to store the inputs.

#### Print Day in Word (PrintDayInWord.java) (nested-if)

Write a program called `PrintDayInWord` that prompts user for an integer 0, 1, 2, ..., 6, or other. The program shall read the input as `int`; and print "Sunday", "Monday", ..., "Saturday", or "Not a valid day", respectively. You are required to use a "nested-if" statement in this program.

##### Test Cases
No. Sample Input Sample Output
`1`
`0`
`Enter the day number: Sundaybye`
`2`
`6`
`Enter the day number: Saturdaybye`
`3`
`9`
`Enter the day number: Not a valid daybye`
##### Hints
```      // Declare variables
int dayNumber;   // The input number
......
// Prompt and read input as "int"
......

// Using nested-if to handle the 8 cases (0 to 6 and others)
if (dayNumber == 0) {   // double-equal for comparison
......
} else if (dayNumber == 1) {
......
} else if (......) {
......
} else {
......
}```

#### Print Number in Word (PrintNumberInWord.java) (switch-case)

Write a program called `PrintNumberInWord` that prompts user for an integer 0, 1, 2, ..., 9, or other. The program shall read the input as `int`; and print "ZERO", "ONE", "TWO", ..., "NINE", or "OTHER", respectively. You are required to use a "switch-case" statement in this program.

##### Test Cases
No. Sample Input Sample Output
`1`
`0`
`Enter a number: ZERObye!`
`2`
`6`
`Enter a number: SIXbye!`
`3`
`-1`
`Enter a number: OTHERbye!`
##### Hints
```      // Declare variables
int numberIn;   // The input number
......

// Using switch-case to handle 11 cases (0 to 9 and others)
switch (numberIn) {
case 1:
System.out.println(...); break;  // "break" needed at the end of every "case"
case 2:
System.out.println(...); break;
......;
......;
default:
......;  // "break" not needed for "default"
}```

#### Rectangle Computation (RectangleComputation.java) (Type int)

Write a program called `RectangleComputation` that prompts user for the length and width of a rectangle in integer. The program shall read the inputs as `int`; compute the perimeter and area of the rectangle; and print the results.

##### Test Cases
No. Sample Input Sample Output
`1`
`9 8 `
`Enter the length:  Enter the width:  The perimeter is: 34 The area is: 72 `
`2`
`8 9 `
`Enter the length:  Enter the width:  The perimeter is: 34 The area is: 72 `
`3`
`1 1 `
`Enter the length:  Enter the width:  The perimeter is: 4 The area is: 1 `
##### Hints

Use `int` variables `length`, `width`, `area`, `perimeter` to store the inputs and results.

#### Circle Computation (CircleComputation.java) (Type double and printf())

Write a program called `CircleComputation` that prompts user for the radius of a circle in floating point number. The program shall read the input as `double`; compute the diameter, circumference, and area of the circle in `double`; and print the values rounded to 2 decimal places. Use System-provided constant `Math.PI` for pi.

The formulas are:

```   area = Math.PI * radius * radius;
circumference = 2.0 * Math.PI * radius;```
##### Test Cases
No. Sample Input Sample Output
`1`
`1.2`
`Enter the radius: Surface Area is: 18.10Volume is: 7.24`
`2`
`1`
`Enter the radius: Surface Area is: 12.57Volume is: 4.19`
`3`
`0.12e2`
`Enter the radius: Surface Area is: 1809.56Volume is: 7238.23`
`4`
`0`
`Enter the radius: Surface Area is: 0.00Volume is: 0.00 `
##### Hints
1. Use `double` variables `radius`, `diameter`, `circumference` and `area` to store the input and results.
2. Use `in.nextDouble()` to read a `double`.
3. Use `System.out.printf()` with specifier `%.2f` to print a `double`, rounded to 2 decimal places; and `%n` to print a newline. For example,
4. `   System.out.printf("Diameter is: %.2f%n", diameter);`

#### Sphere Computation (SphereComputation.java) (Type double and printf())

Write a program called `SphereComputation` that prompts user for the radius of a sphere in floating point number. The program shall read the input as `double`; compute the volume and surface area of the sphere in `double`; and print the values rounded to 2 decimal places. Use System-provided constant `Math.PI` for pi.

The formulas are:

```   surfaceArea = 4 * Math.PI * radius * radius;
volume = 4 /3 * Math.PI * radius * radius * radius;   // But this does not work?! Why?```
##### Test Cases
No. Sample Input Sample Output
`1`
`1.2`
`Enter the radius: Surface Area is: 18.10Volume is: 7.24`
`2`
`1`
`Enter the radius: Surface Area is: 12.57Volume is: 4.19`
`3`
`0.12e2`
`Enter the radius: Surface Area is: 1809.56Volume is: 7238.23`
`4`
`0`
`Enter the radius: Surface Area is: 0.00Volume is: 0.00 `
##### Hints
1. Use `double` variables `radius`, `volume` and `surfaceArea` to store the input and results.
2. Use `in.nextDouble()` to read a `double`.
3. Use `System.out.printf()` with specifier `%.2f` to print a `double` rounded to 2 decimal places; and `%n` to print a newline. For example,
4. `   System.out.printf("Volume is: %.2f%n", volume);`

#### Cylinder Computation (CylinderComputation.java) (Type double and printf())

Write a program called `CylinderComputation` that prompts user for the base radius and height of a cylinder in floating point number. The program shall read the inputs as `double`; compute the base area, surface area, and volume of the cylinder; and print the values rounded to 2 decimal places. Use System-provided constant `Math.PI` for pi.

The formulas are:

```   baseArea = Math.PI * radius * radius;
surfaceArea = 2.0 * Math.PI * radius * height + 2.0 * baseArea;
volume = baseArea * height;```
##### Test Cases
No. Sample Input Sample Output
`1`
`11`
`Enter the radius: Enter the height: Base area is: 3.14Surface area is: 12.57Volume is: 3.14`
`2`
`1.12.2`
`Enter the radius: Enter the height: Base area is: 3.80Surface area is: 22.81Volume is: 8.36`
`3`
`31.1e2`
`Enter the radius: Enter the height: Base area is: 28.27Surface area is: 2130.00Volume is: 3110.18 `
##### Hints
1. Use `double` variables `radius`, `height`, `baseArea`, `surfaceArea` and `volume` to store the inputs and results. Take note that spaces are not allowed in names.
2. Use `in.nextDouble()` to read a `double`.
3. Use `System.out.printf()` with specifier `%.2f` to print a `double`, rounded to 2 decimal places; and `%n` to print a newline. For example,
4. `   System.out.printf("Base Area is: %.2f%n", baseArea);`

#### Swap Contents of Two Variables (SwapIntegers.java) (swap contents)

Write a program called `SwapIntegers` that prompts user for two integers. The program shall read the inputs as `int`, save in two variables called `number1` and `number2`; swap the contents of the two variables; and print the results.

##### Test Cases
No. Sample Input Sample Output
`1`
`58`
`Enter first integer: Enter second integer: After the swap, first integer is: 8, second integer is: 5`
`2`
`9-9`
`Enter first integer: Enter second integer: After the swap, first integer is: -9, second integer is: 9`
`3`
`1111`
`Enter first integer: Enter second integer: After the swap, first integer is: 11, second integer is: 11`
##### Hints

To swap the contents of two variables `x` and `y`, you need to introduce a temporary storage, say `temp`, and do:

```temp <- x
x <- y
y <- temp
```

### Decisions and Loops

#### Sum and Average of Running Integers (SumAverage.java) (for-loop)

Write a program called `SumAverage` that prompts user for a lowerbound and an upperbound. The program shall read the inputs as `int`; compute the sum (in `int`) and average (in `double`) of the running integers from the lowerbound to the upperbound (both inclusive); and print the sum (`int`) and average (`double`) rounded to 2 decimal places.

##### Test Cases
No. Sample Input Sample Output
`1`
`1100`
`Enter the lowerbound: Enter the upperbound: The sum is: 5050The average is: 50.50`
`2`
`11000`
`Enter the lowerbound: Enter the upperbound: The sum is: 500500The average is: 500.50`
`3`
`10999`
`Enter the lowerbound: Enter the upperbound: The sum is: 499455The average is: 504.50`
`4`
`-55`
`Enter the lowerbound: Enter the upperbound: The sum is: 0The average is: 0.00`
##### Hints
```      // Declare variables
int lowerbound, upperbound, sum = 0;
double average;
......

// Prompt and read inputs as "int"
......

// Compute sum using a for-loop
for (int number = ...; number <= ...; ++number) {
sum += number;
}

// Compute average
// Take note that int/int gives int. Type casting needed.
// The total count is (upperbound - lowerbound + 1)
average = ......

// Display results
......```

#### Factorial (Factorial.java) (for-loop)

Write a program called `Factorial` that prompts user for an integer `n` and prints the factorial of `n`. Use an `int` to store the factorial. Assume that `n <= 12` (because factorial of 13 is outside the range of `int`).

The formula is:

`   factorial(n) = 1*2*3*4*...*n   // product of 1 to n`
##### Test Cases
No. Sample Input Sample Output
`1`
`12`
`Enter an integer: The Factorial of 12 is: 479001600`
`2`
`5`
`Enter an integer: The Factorial of 5 is: 120`
`3`
`1`
`Enter an integer: The Factorial of 1 is: 1 `
##### Hints

Use an `int` variable called `product` initialized to 1; and a for-loop to accumulate into the `product`.

#### Factorial in long (FactorialLong.java) (for-Loop & Type long)

Write a program called `FactorialLong` that prompts user for an integer `n`. The program shall read the input as an `int`; compute the factorial of `n` in `long`; and print the result.

In this exercise, we use a `long` to compute and store the factorial. Take note that with `int`, you can store factorial upto 12 (9 digits); with `long`, you can store factorial upto 20 (19 digits).

The formula is:

`   factorial(n) = 1*2*3*4*...*n   // product of 1 to n`
##### Test Cases
No. Sample Input Sample Output
`1`
`13`
`Enter an integer: The Factorial of 13 is: 6227020800`
`2`
`20`
`Enter an integer: The Factorial of 20 is: 2432902008176640000`
`3`
`1`
`Enter an integer: The Factorial of 1 is: 1 `

#### Income Tax Calculator (IncomeTaxCalculator.java) (Decision)

The progressive income tax rate is mandated as follows: The first \$20000 of taxable income is tax exempted; the next \$20000 is taxed at 10%; the next \$20000 is taxed at 20%; and the rest is taxed at 30%. For example, suppose that the taxable income is \$85000, the income tax payable is \$20000*0% + \$20000*10% + \$20000*20% + \$25000*30%.

Write a program called `IncomeTaxCalculator` that reads the taxable income (in `int`). The program shall calculate the income tax payable (in `double`); and print the result rounded to 2 decimal places.

##### Test Cases
No. Sample Input Sample Output
`1`
`20000`
`Enter the taxable income: \$The income tax payable is: \$0.00`
`2`
`20001`
`Enter the taxable income: \$The income tax payable is: \$0.10`
`3`
`25000`
`Enter the taxable income: \$The income tax payable is: \$500.00`
`4`
`40000`
`Enter the taxable income: \$The income tax payable is: \$2000.00`
`5`
`50000`
`Enter the taxable income: \$The income tax payable is: \$4000.00`
`6`
`60000`
`Enter the taxable income: \$The income tax payable is: \$6000.00`
`7`
`85000`
`Enter the taxable income: \$The income tax payable is: \$13500.00 `
##### Hints
```      // Declare constants first (variables may use these constants)
// The keyword "final" marked these as constant (i.e., cannot be changed).
// Use uppercase words joined with underscore to name constants
final double TAX_RATE_ABOVE_20K = 0.1;
final double TAX_RATE_ABOVE_40K = 0.2;
final double TAX_RATE_ABOVE_60K = 0.3;

// Declare variables
int taxableIncome;
double taxPayable;
......

// Compute tax payable in "double" using a nested-if to handle 4 cases
if (taxableIncome <= 20000) {         // [0, 20000]
taxPayable = ......;
} else if (taxableIncome <= 40000) {  // [20001, 40000]
taxPayable = ......;
} else if (taxableIncome <= 60000) {  // [40001, 60000]
taxPayable = ......;
} else {                              // [60001, ]
taxPayable = ......;
}
......```

#### Pension Contribution Calculator (PensionContributionCalculator.java) (Decision)

The pension fund contribution of an employee is mandated as follows: For employee aged 55 and below, the employee contributes 20% of the monthly salary (subjected to a ceiling stated below) and the employer contributes 17%. For employee aged above 55 to 60, the employee contributes 13% and the employer contributes 13%. For employee aged above 60 to 65, the employee contributes 7.5% and the employer contributes 9%. For employee aged above 65, the employee contributes 5% and the employer contributes 7.5%. The salary ceiling that attracts contribution is capped at \$6000. In other words, if an employee earns \$6800, only \$6000 attracts employee's and employer's contributions, the remaining \$800 does not.

Write a program called `PensionContributionCalculator` that reads the monthly salary and the age (in `int`) of an employee. Your program shall calculate the employee's, employer's and total contributions (in `double`); and print the results rounded to 2 decimal places.

##### Test Cases
No. Sample Input Sample Output
`1`
`300030`
`Enter the monthly salary: \$Enter the age: The employee's contribution is: \$600.00The employer's contribution is: \$510.00The total contribution is: \$1110.00`
`2`
`412355`
`Enter the monthly salary: \$Enter the age: The employee's contribution is: \$824.60The employer's contribution is: \$700.91The total contribution is: \$1525.51`
`3`
`412356`
`Enter the monthly salary: \$Enter the age: The employee's contribution is: \$535.99The employer's contribution is: \$535.99The total contribution is: \$1071.98`
`4`
`412360`
`Enter the monthly salary: \$Enter the age: The employee's contribution is: \$535.99The employer's contribution is: \$535.99The total contribution is: \$1071.98`
`5`
`412361`
`Enter the monthly salary: \$Enter the age: The employee's contribution is: \$309.22The employer's contribution is: \$371.07The total contribution is: \$680.30`
`6`
`412365`
`Enter the monthly salary: \$Enter the age: The employee's contribution is: \$309.22The employer's contribution is: \$371.07The total contribution is: \$680.30`
`7`
`412366`
`Enter the monthly salary: \$Enter the age: The employee's contribution is: \$206.15The employer's contribution is: \$309.22The total contribution is: \$515.38`
`8`
`600050`
`Enter the monthly salary: \$Enter the age: The employee's contribution is: \$1200.00The employer's contribution is: \$1020.00The total contribution is: \$2220.00`
`9`
`889950`
`Enter the monthly salary: \$Enter the age: The employee's contribution is: \$1200.00The employer's contribution is: \$1020.00The total contribution is: \$2220.00 `
##### Hints
```      // Declare constants
final int SALARY_CEILING = 6000;
final double EMPLOYEE_RATE_55_AND_BELOW = 0.2;
final double EMPLOYER_RATE_55_AND_BELOW = 0.17;
final double EMPLOYEE_RATE_55_TO_60 = 0.13;
final double EMPLOYER_RATE_55_TO_60 = 0.13;
final double EMPLOYEE_RATE_60_TO_65 = 0.075;
final double EMPLOYER_RATE_60_TO_65 = 0.09;
final double EMPLOYEE_RATE_65_ABOVE = 0.05;
final double EMPLOYER_RATE_65_ABOVE = 0.075;

// Declare variables
int salary, age;     // to be input
int contributableSalary;
double employeeContribution, employerContribution, totalContribution;
......

// Check the contribution cap
contributableSalary = ......

// Compute various contributions in "double" using a nested-if to handle 4 cases
if (age <= 55) {         // 55 and below
......
} else if (age <= 60) {  // (60, 65]
......
} else if (age <= 65) {  // (55, 60]
......
} else {                 // above 65
......
}
......```

#### Income Tax Calculator with Sentinel (IncomeTaxCalculatorSentinel.java) (Decision & Loop)

Based on the previous `IncomeTaxCalculator`, write a program called `IncomeTaxCalculatorSentinel` which shall repeat the calculations until user enter -1. This -1 is known as the sentinel (or terminating) value in programming.

##### Test Cases
No. Sample Input Sample Output
`1`
`1234523456456786123489123-1`
`Enter the taxable income (or -1 to end): \$The income tax payable is: \$0.00Enter the taxable income (or -1 to end): \$The income tax payable is: \$345.60Enter the taxable income (or -1 to end): \$The income tax payable is: \$3135.60Enter the taxable income (or -1 to end): \$The income tax payable is: \$6370.20Enter the taxable income (or -1 to end): \$The income tax payable is: \$14736.90Enter the taxable income (or -1 to end): \$bye!`
`2`
`98765-1`
`Enter the taxable income (or -1 to end): \$The income tax payable is: \$17629.50Enter the taxable income (or -1 to end): \$bye!`
`3`
`-1`
`Enter the taxable income (or -1 to end): \$bye! `
##### Hints
```      // Declare constants first
final int SENTINEL = -1;    // Terminating value for input
......

// Declare constants and variables
int taxableIncome;
double taxPayable;
......

// Read the first input to "seed" the while loop
System.out.print("Enter the taxable income (or -1 to end): \$");
taxableIncome = in.nextInt();

while (taxableIncome != SENTINEL) {
// Compute tax payable in "double" using a nested-if to handle 4 cases
......

// Print result rounded to 2 decimal places
......

System.out.print("Enter the taxable income (or -1 to end): \$");
taxableIncome = in.nextInt();
// Repeat the loop body, only if the input is not the SENTINEL value.
// Take note that you need to repeat these two statements inside/outside the loop!
}
System.out.println("bye!");```

#### Pension Contribution Calculator with Sentinel (PensionContributionCalculatorSentinel.java) (Decision & Loop)

##### Test Cases
No. Sample Input Sample Output
`1`
`512351512364-1`
`Enter the monthly salary (or -1 to end): \$Enter the age: The employee's contribution is: \$1024.60The employer's contribution is: \$870.91The total contribution is: \$1895.51Enter the monthly salary (or -1 to end): \$Enter the age: The employee's contribution is: \$384.22The employer's contribution is: \$461.07The total contribution is: \$845.30Enter the monthly salary (or -1 to end): \$bye!`
`2`
`123421-1`
`Enter the monthly salary (or -1 to end): \$Enter the age: The employee's contribution is: \$246.80The employer's contribution is: \$209.78The total contribution is: \$456.58Enter the monthly salary (or -1 to end): \$bye!`
`3`
`-1`
`Enter the monthly salary (or -1 to end): \$bye! `
##### Hints
```      // Read the first input to "seed" the while loop
System.out.print("Enter the monthly salary (or -1 to end): \$");
salary = in.nextInt();

while (salary != SENTINEL) {
// Read the rest of inputs
System.out.print("Enter the age: ");
age = in.nextInt();

......
......

// Read the next input and repeat
System.out.print("Enter the monthly salary (or -1 to end): \$");
salary = in.nextInt();
}```

#### Salesperson Salary (SalespersonSalary.java) (Decision & Loop)

A company pays its salesperson on a base-salary-plus-commission basis. A salesperson receives \$1000 base salary plus 15% of their gross sales as commission. For example, a salesperson with gross sales of \$18,000 receives \$1000 + \$18000*15%.

Write a program to compute the salary of ALL the salespersons in the company. Your program shall use a loop to continuously input each salesperson's gross sales (as `int`); compute that salesperson's salary (in `double`); and display the results rounded to 2 decimal places. The program shall terminate in response to input of -1.

##### Test Cases
No. Sample Input Sample Output
`1`
`100002000030000-1`
`Enter sales in dollars (or -1 to end): Salary is: \$2500.00Enter sales in dollars (or -1 to end): Salary is: \$4000.00Enter sales in dollars (or -1 to end): Salary is: \$5500.00Enter sales in dollars (or -1 to end): bye`
`2`
`1234567890-1`
`Enter sales in dollars (or -1 to end): Salary is: \$2851.75Enter sales in dollars (or -1 to end): Salary is: \$11183.50Enter sales in dollars (or -1 to end): bye`
`3`
`0-1`
`Enter sales in dollars (or -1 to end): Salary is: \$1000.00Enter sales in dollars (or -1 to end): bye`
`4`
`-1`
`Enter sales in dollars (or -1 to end): bye `
##### Hints
```      // Declare constants
// The keyword "final" marked these as constant (i.e., cannot changed).
// Use uppercase words joined with underscore to name constants
final double BASE_SALARY = 1000;
final double COMMISSION_RATE = 0.15;
final int SENTINEL = -1;        // Terminating value for input

// Declare variables
int sales;       // Input gross sales
double salary;   // Salary to be computed
......

// Read the first input to "seed" the while loop
System.out.print("Enter sales in dollars (or -1 to end): ");
sales =  in.nextInt();

while (sales != SENTINEL) {
// Compute the salary in "double"
......

// Print results rounded to 2 decimal places
......

System.out.print("Enter sales in dollars (or -1 to end): ");
sales =  in.nextInt();
// Repeat the loop body, only if the input is not the SENTINEL value.
// Take note that you need to repeat these two statements inside/outside the loop!
}
......```

#### Sales Tax (SalesTax.java) (Decision & Loop)

A sales tax of 7% is levied on all goods and services consumed. It is also mandatory that all the price tags should include the sales tax. For example, if an item has a price tag of \$107, the actual price is \$100 and \$7 goes to the sales tax.

Write a program using a loop to continuously input the tax-inclusive price (as `double`); compute the actual price and the sales tax (in `double`); and print the results rounded to 2 decimal places. The program shall terminate in response to input of -1; and print the total price, total actual price, and total sales tax.

##### Test Cases
No. Sample Input Sample Output
`1`
`107214321-1`
`Enter the tax-inclusive price in dollars (or -1 to end): Actual Price is: \$100.00, Sales Tax is: \$7.00Enter the tax-inclusive price in dollars (or -1 to end): Actual Price is: \$200.00, Sales Tax is: \$14.00Enter the tax-inclusive price in dollars (or -1 to end): Actual Price is: \$300.00, Sales Tax is: \$21.00Enter the tax-inclusive price in dollars (or -1 to end): Total Price is: \$642.00Total Actual Price is: \$600.00Total Sales Tax is: \$42.00`
`2`
`123456-1`
`Enter the tax-inclusive price in dollars (or -1 to end): Actual Price is: \$114.95, Sales Tax is: \$8.05Enter the tax-inclusive price in dollars (or -1 to end): Actual Price is: \$426.17, Sales Tax is: \$29.83Enter the tax-inclusive price in dollars (or -1 to end): Total Price is: \$579.00Total Actual Price is: \$541.12Total Sales Tax is: \$37.88`
`3`
`1234.56-1`
`Enter the tax-inclusive price in dollars (or -1 to end): Actual Price is: \$1153.79, Sales Tax is: \$80.77Enter the tax-inclusive price in dollars (or -1 to end): Total Price is: \$1234.56Total Actual Price is: \$1153.79Total Sales Tax is: \$80.77`
`4`
`-1`
`Enter the tax-inclusive price in dollars (or -1 to end): Total Price is: \$0.00Total Actual Price is: \$0.00Total Sales Tax is: \$0.00 `
##### Hints
```      // Declare constants
final double SALES_TAX_RATE = 0.07;
final int SENTINEL = -1;        // Terminating value for input

// Declare variables
double price, actualPrice, salesTax;  // inputs and results
double totalPrice = 0.0, totalActualPrice = 0.0, totalSalesTax = 0.0;  // to accumulate
......

// Read the first input to "seed" the while loop
System.out.print("Enter the tax-inclusive price in dollars (or -1 to end): ");
price =  in.nextDouble();

while (price != SENTINEL) {
// Compute the tax
......
// Accumulate into the totals
......
// Print results
......

System.out.print("Enter the tax-inclusive price in dollars (or -1 to end): ");
price =  in.nextDouble();
// Repeat the loop body, only if the input is not the sentinel value.
// Take note that you need to repeat these two statements inside/outside the loop!
}
// print totals
......```

#### Harmonics Sum (HarmonicSum.java) (Decision & Loop)

Write a program that prompts user for the maximum denominator (`n`). The program shall read the input as `int`; compute the sum of the Harmonic series upto `n`; and print the result (in full precision).

The Harmonic Series is:

`   Sum = 1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + ..... + 1/n`

You are to compute two sums: from left-to-right and from right-to-left. Also compute their absolute difference.

##### Test Cases
No. Sample Input Sample Output
`1`
`10000`
`Enter the max denominator: The sum from left-to-right is: 9.787606036044348The sum from right-to-left is: 9.787606036044386The absolute difference is: 3.730349362740526E-14`
`2`
`1000`
`Enter the max denominator: The sum from left-to-right is: 7.485470860550343The sum from right-to-left is: 7.485470860550341The absolute difference is: 2.6645352591003757E-15`
`3`
`1`
`Enter the max denominator: The sum from left-to-right is: 1.0The sum from right-to-left is: 1.0The absolute difference is: 0.0 `
##### Hints
```      // Declare variables
int maxDenominator;   // to be input
double sumL2R = 0.0, sumR2L = 0.0, absDiff;  // to compute these in "double"
......

// Prompt and read inputs as "int"
......

// Compute sum from left-to-right in "double"
for (int denominator = 1; denominator <= maxDenominator; denominator++) {
......
// Take note that int/int gives int.
}

// Compute sum from right-to-left in "double"
for (int denominator = maxDenominator; denominator >= 1; denominator--) {
......
}

// Compute the absolute difference in "double"
// absDiff = ......
// if (absDiff < 0) absDiff = -absDiff;

// Print results in full precision using println()
......```

#### Compute PI (A) (ComputePIa.java) (Decision & Loop)

Write a program to compute the value of PI, using the following series:

`   PI = 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + 1/13 .....)`

Your program shall prompt the user for the "maximum denominator" used in the computation.

Display the computed value of PI to 10 decimal places.

##### Test Cases
No. Sample Input Sample Output
`1`
`10000`
`Enter the maximum denominator: The PI computed is: 3.1413926536`
`2`
`1000`
`Enter the maximum denominator: The PI computed is: 3.1395926556`
`3`
`100`
`Enter the maximum denominator: The PI computed is: 3.1215946526 `
##### Hints
```      int maxDenominator;  // to be input
double sum = 0.0;
......

for (int denominator = 1; denominator <= maxDenominator; denominator += 2) {
// denominator = 1, 3, 5, 7, ..., maxDenominator
if (denominator % 4 == 1) {
......
} else if (denominator % 4 == 3) {
// subtract from sum
......
} else {
System.out.println("impossible - error in logic");
}
}```

#### Sum of Digits of an Integer (SumOfDigitsInt.java) (Loop & Modulus/Division)

Write a program that prompts user for a positive integer. The program shall read the input as `int`; compute and print the sum of all its digits. No input validation is needed.

##### Test Cases
No. Sample Input Sample Output
`1`
`12345`
`Enter a positive integer: The sum of all digits is: 15`
`2`
`67890`
`Enter a positive integer: The sum of all digits is: 30`
`3`
`1`
`Enter a positive integer: The sum of all digits is: 1 `
##### Hints
```      // Declare variables
int inNumber;   // to be input
int inDigit;    // each digit
int sum = 0;
......

// Prompt and read inputs as "int"
......

// Extract the "last" digit repeatedly using a while-loop with modulus/divide operations
while (inNumber > 0) {
inDigit = inNumber % 10; // extract the "last" digit
inNumber /= 10;          // drop "last" digit
sum = ......
}
......```

#### Reverse of an Integer (ReverseInt.java) (Loop & Modulus/Division)

Write a program that prompts user for a positive integer. The program shall read the input as `int`; and print the reverse of the input integer. No input validation needed.

##### Test Cases
No. Sample Input Sample Output
`1`
`12345`
`Enter a positive integer: The reverse is: 54321`
`2`
`67890`
`Enter a positive integer: The reverse is: 09876`
`3`
`1`
`Enter a positive integer: The reverse is: 1`
##### Hints
```      // Declare variables
int inNumber;   // to be input
int inDigit;    // each digit
......

// Extract and drop the "last" digit repeatedly using a while-loop with modulus/divide operations
while (inNumber > 0) {
inDigit = inNumber % 10; // extract the "last" digit
// Print this digit (which is extracted in reverse order)
......
inNumber /= 10;          // drop "last" digit and repeat
}
......```

#### Input Validation (InputValidation.java) (loop & boolean flag)

Your program often needs to validate the user's inputs, e.g., marks shall be between 0 and 100.

Write a program that prompts user for an integer between 0-10 or 90-100. The program shall read the input as an `int`; and repeat until the user enters a valid input.

##### Test Cases
No. Sample Input Sample Output
`1`
`-15010195`
`Enter a number between 0-10 or 90-100: Invalid input, try again...Enter a number between 0-10 or 90-100: Invalid input, try again...Enter a number between 0-10 or 90-100: Invalid input, try again...Enter a number between 0-10 or 90-100: You have entered: 95`
`2`
`-10`
`Enter a number between 0-10 or 90-100: Invalid input, try again...Enter a number between 0-10 or 90-100: You have entered: 0`
`3`
`5`
`Enter a number between 0-10 or 90-100: You have entered: 5 `
##### Hints
```      // Declare variables
int numberIn;      // to be input
boolean isValid;   // boolean flag to control the loop
......

// Use a do-while loop controlled by a boolean flag
// to repeatably read the input until a valid input is entered
isValid = false;   // default assuming input is not valid
do {
......

// Validate input by setting the boolean flag accordingly
if (numberIn ......) {
isValid = true;   // exit the loop
} else {
System.out.println(......);  // Print error message and repeat
}
} while (!isValid);
......```

#### Average with Input Validation (AverageWithInputValidation.java) (Loop & boolean flag)

Write a program that prompts user for the mark (between 0-100 as `int`) of 3 students; computes the average (in `double`); and prints the result rounded to 2 decimal places. Your program needs to perform input validation.

##### Test Cases
No. Sample Input Sample Output
`1`
`358799`
`Enter the mark (0-100) for student 1: Enter the mark (0-100) for student 2: Enter the mark (0-100) for student 3: The average is: 73.67`
`2`
`56101-19945`
`Enter the mark (0-100) for student 1: Enter the mark (0-100) for student 2: Invalid input, try again...Enter the mark (0-100) for student 2: Invalid input, try again...Enter the mark (0-100) for student 2: Enter the mark (0-100) for student 3: The average is: 66.67`
`3`
`101100-1050`
`Enter the mark (0-100) for student 1: Invalid input, try again...Enter the mark (0-100) for student 1: Enter the mark (0-100) for student 2: Invalid input, try again...Enter the mark (0-100) for student 2: Enter the mark (0-100) for student 3: The average is: 50.00 `
##### Hints
```      // Declare constant
final int NUM_STUDENTS = 3;

// Declare variables
int numberIn;
boolean isValid;   // boolean flag to control the input validation loop
int sum = 0;
double average;
......

for (int studentNo = 1; studentNo <= NUM_STUDENTS; ++studentNo) {
// Prompt user for mark with input validation
......
isValid = false;   // reset for each student assuming input is not valid
do {
......
// If input is valid, eet isValid = true to exit the loop
// Else, print error message and repeat
......
} while (!isValid);

sum += ......;
}
......```

### Nested-Loops

#### Checker Pattern (Nested-Loops)

Write a program that prompts user for the size of the pattern (in `int`); and prints the checker pattern as shown in the sample output.

##### Test Cases
No. Sample Input Sample Output
`1`
`5`
`Enter the size: # # # # #  # # # # # # # # # #  # # # # # # # # # # `
`2`
`3`
`Enter the size: # # #  # # # # # # `
`3`
`1`
`Enter the size: #  `
##### Hints
```      // Outer loop to print ALL the rows
for (int row = 1; row <= size; row++) {
// Use print() to print a space, if needed, before printing this row
......
// Inner loop to print ALL the columns of ONE row
for (int col = 1; col <= size; col++) {
// Use print() here
......
}
// Print a newline after all the columns
System.out.println();
}```

#### Triangular Pattern (A) (Nested-Loops)

Write a program that prompts user for the size of the pattern; and prints the triangular pattern as shown in the sample output.

##### Test Cases
No. Sample Input Sample Output
`1`
`5`
`Enter the size: ***************`
`2`
`4`
`Enter the size: **********`
`3`
`1`
`Enter the size: * `
##### Hints
```      for (int row = 1; row <= size; row++) {
for (int col = 1; col <= size; col++) {
// if (row >= col) print *
......
}
// Print a newline after all the columns
......
}```

#### Triangular Pattern (C) (Nested-Loops)

Write a program that prompts user for the size of the pattern; and prints the triangular pattern as shown in the sample output.

##### Test Cases
No. Sample Input Sample Output
`1`
`5`
`Enter the size: ***** ****  ***   **    *`
`2`
`4`
`Enter the size: **** ***  **   *`
`3`
`1`
`Enter the size: * `
##### Hints
```      for (int row = 1; row <= size; row++) {
for (int col = 1; col <= size; col++) {
// if (row <= col) print *
// else print a space (needed to push the * to the right)
......
}
// Print a newline after all the columns
......
}```

#### Z Pattern (Nested-Loops)

Write a program that prompts user for the size of the pattern; and print the Z-pattern as shown in the sample output.

##### Test Cases
No. Sample Input Sample Output
`1`
`5`
`Enter the size: *****   *   *   *   *****`
`2`
`3`
`Enter the size: *** * ***`
`3`
`1`
`Enter the size: * `
##### Hints

The formula for the diagonal is `row + col = size + 1`, with `row` and `col` begin from 1.

The algorithm is:

```if row is 1, or row is n, or row + col = n + 1, print *
else print a space```

#### Box with Cross (Nested-Loops)

Write a program that prompts user for the size of the pattern; and prints the box-with-cross pattern as shown in the sample output.

##### Test Cases
No. Sample Input Sample Output
`1`
`8`
`Enter the size: *********+    +** +  + **  ++  **  ++  ** +  + **+    +*********`
`2`
`7`
`Enter the size: ********+   +** + + **  +  ** + + **+   +********`
`3`
`1`
`Enter the size: * `
##### Hints

The formula for the main diagonal is `row = col`; while the opposite diagonal is `row + col = n + 1`, where `row` and `col` begin from 1.

The algorithm is:

```if row is 1, or row is n, or col is 1, or col is n, print *
else if row = col, or row + col = n + 1, print +
else print a space```

#### Triangular Number Pattern (Nested-Loops)

Write a program that prompts user for the size of the pattern; and prints the triangular number pattern as shown in the sample output.

##### Test Cases
No. Sample Input Sample Output
`1`
`7`
`Enter the size: 1234567 123456  12345   1234    123     12      1`
`2`
`5`
`Enter the size: 12345 1234  123   12    1`
`3`
`1`
`Enter the size: 1 `

#### Multiplication Table (Nested-Loops)

Write a program that prompts user for the size; and prints the multiplication table of that size.

##### Test Cases
No. Sample Input Sample Output
`1`
`9`
`Enter the size of the table:  * |   1   2   3   4   5   6   7   8   9===+==================================== 1 |   1   2   3   4   5   6   7   8   9 2 |   2   4   6   8  10  12  14  16  18 3 |   3   6   9  12  15  18  21  24  27 4 |   4   8  12  16  20  24  28  32  36 5 |   5  10  15  20  25  30  35  40  45 6 |   6  12  18  24  30  36  42  48  54 7 |   7  14  21  28  35  42  49  56  63 8 |   8  16  24  32  40  48  56  64  72 9 |   9  18  27  36  45  54  63  72  81`
`2`
`5`
`Enter the size of the table:  * |   1   2   3   4   5===+==================== 1 |   1   2   3   4   5 2 |   2   4   6   8  10 3 |   3   6   9  12  15 4 |   4   8  12  16  20 5 |   5  10  15  20  25`
`3`
`1`
`Enter the size of the table:  * |   1===+==== 1 |   1 `

#### Hill Pattern (Nested-Loops)

Write a program that prompts user for the number of rows; and prints the Hill pattern as shown in the sample output.

##### Test Cases
No. Sample Input Sample Output
`1`
`5	 `
`Enter the rows:      ^        ^^^      ^^^^^    ^^^^^^^  ^^^^^^^^^ `
`2`
`4 `
`Enter the rows:     ^      ^^^    ^^^^^  ^^^^^^^ `
`3`
`3 `
`Enter the rows:    ^    ^^^  ^^^^^ `
##### Hints
```      for (int row = 1; ......) {
// numCol = 2*numRows - 1
for (int col = 1; ......) {
if ((row + col >= numRows + 1) && (row >= col - numRows + 1)) {
......;
} else {
......;
}
}
......;
}```

or, use 2 sequential inner loops to print the columns:

```      for (int row = 1; row <= rows; row++) {
for (int col = 1; col <= rows; col++) {
if ((row + col >= rows + 1)) {
......
} else {
......
}
}
for (int col = 2; col <= rows; col++) {  // skip col = 1
if (row >= col) {
......
} else {
......
}
}
......
}```

### String and char Operations

#### Reverse String (String & char)

Write a program that prompts user for a string; and prints the string in the reverse order.

##### Test Cases
No. Sample Input Sample Output
`1`
`abcdefg`
`Enter a String: The reverse is: gfedcba`
`2`
`12345`
`Enter a String: The reverse is: 54321`
`3`
`a`
`Enter a String: The reverse is: a `
##### Hints
1. For a `String` called `inStr`, you can use `inStr.length()` to get the length of the `String`; and `inStr.charAt(index)` to retrieve the `char` at the `index` position, where `index` begins with 0.
2. Use a for-loop to extract each `char` of the input `String` in the reverse order, and print the extracted `char`. There is no need to save the result.
```      String inStr;   // input String
int inStrLen;   // length of the input String
......

System.out.print("Enter a String: ");
inStr = in.next();   // use next() to read a String
inStrLen = inStr.length();

// Use inStr.charAt(index) in a loop to extract character at "index" from inStr.
// The String's index begins at 0 from the left.
......
for (int charIdx = inStrLen - 1; charIdx >= 0; --charIdx) {  // Process the String from the right
// Print the inStr.charAt(charIdx)
......
}```

#### Phone Keypad (String & char)

On your phone's keypad, the alphabets are mapped to digits as follows: `ABC(2)`, `DEF(3)`, `GHI(4)`, `JKL(5)`, `MNO(6)`, `PQRS(7)`, `TUV(8)`, `WXYZ(9)`.

Write a program called `PhoneKeyPad` which prompts user for a `String` (case insensitive), and converts to a sequence of keypad digits.

You are required to use a "switch-case" statement in this exercise.

##### Test Cases
No. Sample Input Sample Output
`1`
`1800flower`
`Enter a String: The phone number is: 1800356937`
`2`
`HelloWorld`
`Enter a String: The phone number is: 4355696753 `
##### Hints
1. You could use `in.next().toLowerCase()` to read an input `String` and convert it into lowercase to reduce the number of cases.
2. In `switch-case`, you can handle multiple cases as follows:
```      // Declare variables
String inStr;   // input String
int inStrLen;   // length of the input String
char inChar;    // each individual char in the string
......

for (int inCharIdx = 0; inCharIdx < inStrLength; ++inCharIdx) {
inChar = inStr.charAt(inCharIdx);
switch (inChar) {
case 'a': case 'b': case 'c':   // same as: if (inChar == 'a' || inChar == 'b' || inChar == 'c')
System.out.print(2); break;
case 'd': case 'e': case 'f':
......
......
default:
System.out.println("error in input");
}
}```

#### Count Vowels and Digits (String & char)

Write a program that prompts user for a string and counts the number of vowels (a, e, i, o, u, A, E, I, O, U) and digits (0-9) contained in the string. The program shall print the counts and the percentages (rounded to 2 decimal places).

You are required to use a "nested-if" statement in this exercise.

##### Test Cases
No. Sample Input Sample Output
`1`
`testing12345`
`Enter a String: Number of vowels is: 2 (16.67%)Number of digits is: 5 (41.67%)`
`2`
`1string2strings3strings`
`Enter a String: Number of vowels is: 3 (13.04%)Number of digits is: 3 (13.04%)`
`3`
`bcdfghjklmn`
`Enter a String: Number of vowels is: 0 (0.00%)Number of digits is: 0 (0.00%) `
##### Hints
1. Use `in.next().toLowerCase()` to read an input string and convert it into lowercase to reduce the number of cases.
2. To check if a `char c` is a digit, you can use `boolean` expression `(c >= '0' && c <= '9')`; or use built-in `boolean` function `Character.isDigit(c)`.
3. To print a `%` using `printf()`, you need to use `%%`. This is because `%` has a special meaning inside `printf()`, e.g., `%d` and `%f`.

#### Sum of Digits in String (String, char & int)

Write a program that prompts user for a string. The program shall compute and print the sum of all the digits (`'0'` to `'9'`) found in the string. Ignore all the non-digit characters.

##### Test Cases
No. Sample Input Sample Output
`1`
`testing12345`
`Enter a String: The sum of all digits is: 15`
`2`
`1800flower`
`Enter a String: The sum of all digits is: 9`
`3`
`1_2-3@4xyz`
`Enter a String: The sum of all digits is: 10`
`4`
`helloworld`
`Enter a String: The sum of all digits is: 0 `
##### Hints

To check if a `char c` is a digit character `'0'` to `'9'`, you can use either:

1. `boolean` expression `(c >= '0' && c <= '9')`; or
2. built-in `boolean` function `Character.isDigit(c)` which returns `true` if `c` is a digit.

Take note that `char '0'` is represented as code number `48`, ..., `char '5'` as `53`. To convert `char '5'` to `int 5`, subtract it by `char '0'` (which is `int 48`).

In other words, to convert a `char c` to an `int i` (e.g., `'0'` to `0`, ..., `'5'` to `5` - which is needed to be added into the sum), use `i = c - '0'`.

#### Caesar's Code (String, char & int)

Caesar's code is one of the simplest encryption techniques. Each letter in the plaintext is replaced by a letter some fixed number of position (`n`) down the alphabet cyclically. In this exercise, we shall pick `n=3`. That is, `'A'` is replaced by `'D'`, `'B'` by `'E'`, `'C'` by `'F'`, ..., `'X'` by `'A'`, ..., `'Z'` by `'C'`.

Write a program to cipher the caesar's code. The program shall prompt user for a plaintext string consisting of letters only; compute the ciphertext; and print the ciphertext in uppercase. No input validation needed.

##### Test Cases
No. Sample Input Sample Output
`1`
`testing`
`Enter a plaintext string: The ciphertext string is: WHVWLQJ`
`2`
`HELLOWORLD`
`Enter a plaintext string: The ciphertext string is: KHOORZRUOG`
`3`
`ASecretText`
`Enter a plaintext string: The ciphertext string is: DVHFUHWWHAW`
`4`
`AaBbCcXxYyZz`
`Enter a plaintext string: The ciphertext string is: DDEEFFAABBCC`
`5`
`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`
`Enter a plaintext string: The ciphertext string is: DEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZABC `
##### Hints
1. Use `in.next().toUpperCase()` to read an input string and convert it into uppercase to reduce the number of cases.
2. You can use a big nested-if with 26 cases (`'A'-'Z'`). But it is much better to consider `'A'` to `'W'` as one case; `'X'`, `'Y'` and `'Z'` as 3 separate cases.
3. Take note that `char 'A'` is represented as code number `65` and `char 'D'` as `68`. However, `'A' + 3 gives 68`. This is because `char + int` is implicitly casted to `int + int` which returns an `int` value. To obtain a `char` value, you need to perform explicit type casting using `(char)('A' + 3)`. Try printing `('A' + 3)` with and without type casting.

#### An Exchange Cipher (String, char & int)

This simple cipher exchanges `'A'` and `'Z'`, `'B'` and `'Y'`, `'C'` and `'X'`, and so on.

Write a program that prompts user for a plaintext string consisting of letters only. You program shall compute the ciphertext; and print the ciphertext in uppercase. No input validation needed.

##### Test Cases
No. Sample Input Sample Output
`1`
`abcXYZ`
`Enter a plaintext string: The ciphertext string is: ZYXCBA`
`2`
`testing`
`Enter a plaintext string: The ciphertext string is: GVHGRMT`
`3`
`ASecretText`
`Enter a plaintext string: The ciphertext string is: ZHVXIVGGVCG`
`4`
`m`
`Enter a plaintext string: The ciphertext string is: N `
##### Hints
1. Use `in.next().toUpperCase()` to read an input string and convert it into uppercase to reduce the number of cases.
2. You can use a big nested-if with 26 cases (`'A'-'Z'`); or use the following relationship:
```'A' + 'Z' == 'B' + 'Y' == 'C' + 'X' == ... == plainTextChar + cipherTextChar
Hence, cipherTextChar = 'A' + 'Z' - plainTextChar```

#### Bin2Dec (a) (String/char & Number Conversion)

Write a program to convert a binary string to its decimal equivalent. The program shall prompt user for a binary number; read the input as `String`; compute and print its decimal equivalent. No input validation is needed.

##### Test Cases
No. Sample Input Sample Output
`1`
`1011`
`Enter a binary string: The decimal equivalent is: 11`
`2`
`10000011`
`Enter a binary string: The decimal equivalent is: 131`
`3`
`0`
`Enter a binary string: The decimal equivalent is: 0`
`4`
`1`
`Enter a binary string: The decimal equivalent is: 1 `

#### Oct2Dec (String/char & Number Conversion)

Write a program to convert a octal (base 8) string to its decimal equivalent. The program shall prompt user for a octal number; read the input as `String`; compute and print its decimal equivalent. No input validation is needed.

##### Test Cases
No. Sample Input Sample Output
`1`
`12`
`Enter an octal string: The decimal equivalent is: 10`
`2`
`7123`
`Enter an octal string: The decimal equivalent is: 3667`
`3`
`0`
`Enter an octal string: The decimal equivalent is: 0`

#### Palindromic Word (String/char & Two Loop Indexes)

A word that reads the same backward as forward is called a palindrome, e.g., "mom", "dad", "racecar", "madam", and "Radar" (case-insensitive). Write a program called PalindromicWordTest, that prompts user for a word and decides if the input word is a palindrome.

##### Test Cases
No. Sample Input Sample Output
`1`
`Radar`
`Enter a String: "Radar" is palindromic`
`2`
`RaceCar`
`Enter a String: "RaceCar" is palindromic`
`3`
`m`
`Enter a String: "m" is palindromic`
`4`
`Hello`
`Enter a String: "Hello" is not palindromic `
##### Hints
```      // Declare variables
String inStr;           // The input string, need to save for output printing
String inStrLowerCase;  // The input string in lowercase to reduce the cases in comparison
int inStrLen;           // The length of the input string
char forwardChar, backwardChar;   // to compare these two chars, scan forward and backward
boolean isPalindromic;  // boolean flag
......

isPalindromic = true;     // assume it is true, unless our check fails
for (int forwardIdx = 0, backwardIdx = inStrLen - 1; forwardIdx < inStrLen/2; ++forwardIdx, --backwardIdx) {
forwardChar = ......;
backwardChar = ......;
if (forwardChar != backwardChar) {
isPalindromic = false;
break;    // upon the first encounter, no need to go further
}
}
......```

### Arrays

#### Print Array (Array & Loop)

Write a program which prompts user for the number of items in an array (a non-negative integer), reads it, and saves it in an `int` variable called `numItems`. It then prompts user for the values of all the items and saves them in an `int` array called `items`. The program shall then print the contents of the array in the form of `[x1, x2, ..., xn]`. No input validation is needed.

##### Test Cases
No. Sample Input Sample Output
`1`
`53 2 5 6 9`
`Enter the number of items: Enter the value of all items (separated by space): The values are: [3, 2, 5, 6, 9]`
`2`
`288 99`
`Enter the number of items: Enter the value of all items (separated by space): The values are: [88, 99]`
`3`
`199`
`Enter the number of items: Enter the value of all items (separated by space): The values are: [99]`
`4`
`0`
`Enter the number of items: The values are: [] `
##### Hints
```      // Declare variables
int numItems;
int[] items;  // Declare array name, to be allocated after numItems is known
......

// Prompt for a non-negative integer for the number of items;
// and read the input as "int". No input validation.
......

// Allocate the array
items = new int[numItems];

// Prompt and read the items into the "int" array, if array length > 0
if (items.length > 0) {
......
for (int i = 0; i < items.length; ++i) {
......
}
}

// Print array contents, need to handle first item and subsequent items differently
......
for (int i = 0; i < items.length; ++i) {
if (i == 0) {
// Print the first item without a leading commas
......
} else {
// Print the subsequent items with a leading commas
......
}
// or, using a one liner
//System.out.print((i == 0) ? ...... : ......);
}
......```

#### Print Array in Stars (Array & Loop)

Write a program which prompts user for the number of items in an array (a non-negative integer), reads it, and saves it in an `int` variable called `numItems`. It then prompts user for the values of all the items (non-negative integers) and saves them in an `int` array called `items`.

The program shall then print the contents of the array in a graphical form, with the array index and values represented by number of stars. No input validation is needed.

##### Test Cases
No. Sample Input Sample Output
`1`
`5	 7 4 3 0 7 `
`Enter the number of items:  Enter the value of all items (separated by space):  0: *******(7) 1: ****(4) 2: ***(3) 3: (0) 4: *******(7) `
`2`
`2 8 4 `
`Enter the number of items:  Enter the value of all items (separated by space):  0: ********(8) 1: ****(4) `
`3`
`1 9 `
`Enter the number of items:  Enter theh value of all items (separated by space):  0: *********(9) `
`4`
`0 `
`Enter the number of items:  `
##### Hints
```      // Declare variables
int numItems;
int[] items;  // Declare array name, to be allocated after numItems is known
......
......

// Print array contents (in index: number of stars) using a nested-loop
for (int idx = 0; idx < items.length; ++idx) {  // row
System.out.print(idx + ": ");
// Print value as the number of stars
for (int starNo = 1; starNo <= items[idx]; ++starNo) {  // col
System.out.print("*");
}
......
}
......```

#### Grades Statistics (Array & Loop)

Write a program which prompts user for the number of students in a class (a non-negative integer), reads it, and saves it in an `int` variable called `numStudents`. It then prompts user for the grade of each of the students (integer between 0 to 100) and saves them in an `int` array called `grades`. The program shall then compute and print the average (in `double` rounded to 2 decimal places) and minimum/maximum (in `int`). No input validation is needed.

##### Test Cases
No. Sample Input Sample Output
`1`
`3908578`
`Enter the number of students: Enter the grade for student 1: Enter the grade for student 2: Enter the grade for student 3: The average is: 84.33The minimum is: 78The maximum is: 90`
`2`
`59878788776`
`Enter the number of students: Enter the grade for student 1: Enter the grade for student 2: Enter the grade for student 3: Enter the grade for student 4: Enter the grade for student 5: The average is: 83.40The minimum is: 76The maximum is: 98`
`3`
`150`
`Enter the number of students: Enter the grade for student 1: The average is: 50.00The minimum is: 50The maximum is: 50`

Write a program that prompts user for the number of students in a class (a non-negative integer), reads it, and saves it in an `int` variable called `numStudents`. It then prompts user for the grade of each of the students (integer between 0 to 100) and saves them in an `int` array called `grades`.

Assume that the grades are between 0 and 100. The program shall then create 10 histogram bins to contain the counts of grades between 0-9, 10-19, ..., 90-100, respectively, in an `int` array called `bins`; and print the contents of the bins as shown in the sample output. No input validation is needed.

##### Test Cases
No. Sample Input Sample Output
`1`
`79010089860550`
`Enter the number of students: Enter the grade for student 1: Enter the grade for student 2: Enter the grade for student 3: Enter the grade for student 4: Enter the grade for student 5: Enter the grade for student 6: Enter the grade for student 7:  0-  9: 210- 19: 020- 29: 030- 39: 040- 49: 050- 59: 160- 69: 070- 79: 080- 89: 290-100: 2`
`2`
`88845894510009890`
`Enter the number of students: Enter the grade for student 1: Enter the grade for student 2: Enter the grade for student 3: Enter the grade for student 4: Enter the grade for student 5: Enter the grade for student 6: Enter the grade for student 7: Enter the grade for student 8:  0-  9: 110- 19: 020- 29: 030- 39: 040- 49: 250- 59: 060- 69: 070- 79: 080- 89: 290-100: 3`
`3`
`1100`
`Enter the number of students: Enter the grade for student 1:  0-  9: 010- 19: 020- 29: 030- 39: 040- 49: 050- 59: 060- 69: 070- 79: 080- 89: 090-100: 1`
`4`
`0`
`Enter the number of students:  0-  9: 010- 19: 020- 29: 030- 39: 040- 49: 050- 59: 060- 69: 070- 79: 080- 89: 090-100: 0 `
##### Hints
```      // Declare variables
int numStudents;
int[] grades;     // Declare array name, to be allocated after numStudents is known
int[] bins = new int[10];   // int array of 10 histogram bins for 0-9, 10-19, ..., 90-100

......

// Populate the bins
for (int i = 0; i < grades.length; ++i) {
if (grades[i] == 100) {   // Need to handle 90-100 separately as it has 11 items.
++bins[9];
} else {
}
}

// Print the bins
for (int binIdx = 0; binIdx < bins.length; ++binIdx) {
if (binIdx != 9) {   // Need to handle 90-100 separately as it has 11 items.
System.out.printf("%2d-%3d: ", binIdx*10, ....);
} else {
System.out.print(......);
}
System.out.println(bins[binIdx]);
}```

Write a program that prompts user for the number of students in a class (a non-negative integer), reads it, and saves it in an `int` variable called `numStudents`. It then prompts user for the grade of each of the students (integer between 0 to 100) and saves them in an `int` array called `grades`.

Assume that the grades are between 0 and 100. The program shall then create 10 histogram bins to contain the counts of grades between 0-9, 10-19, ..., 90-100, respectively, in an `int` array called `bins`; and print the histogram horizontally as shown in the sample output. No input validation is needed.

##### Test Cases
No. Sample Input Sample Output
`1`
`79010089860550`
`Enter the number of students: Enter the grade for student 1: Enter the grade for student 2: Enter the grade for student 3: Enter the grade for student 4: Enter the grade for student 5: Enter the grade for student 6: Enter the grade for student 7:  0-  9: **10- 19: 20- 29: 30- 39: 40- 49: 50- 59: *60- 69: 70- 79: 80- 89: **90-100: **`
`2`
`88845894510009890`
`Enter the number of students: Enter the grade for student 1: Enter the grade for student 2: Enter the grade for student 3: Enter the grade for student 4: Enter the grade for student 5: Enter the grade for student 6: Enter the grade for student 7: Enter the grade for student 8:  0-  9: *10- 19: 20- 29: 30- 39: 40- 49: **50- 59: 60- 69: 70- 79: 80- 89: **90-100: ***`
`3`
`1100`
`Enter the number of students: Enter the grade for student 1:  0-  9: 10- 19: 20- 29: 30- 39: 40- 49: 50- 59: 60- 69: 70- 79: 80- 89: 90-100: *`
`4`
`0`
`Enter the number of students:  0-  9: 10- 19: 20- 29: 30- 39: 40- 49: 50- 59: 60- 69: 70- 79: 80- 89: 90-100: `

Write a program that prompts user for the number of students in a class (a non-negative integer), reads it, and saves it in an `int` variable called `numStudents`. It then prompts user for the grade of each of the students (integer between 0 to 100) and saves them in an `int` array called `grades`.

Assume that the grades are between 0 and 100. The program shall then create 10 histogram bins to contain the counts of grades between 0-9, 10-19, ..., 90-100, respectively, in an `int` array called `bins`; and print the histogram vertically as shown in the sample output. No input validation is needed.

##### Test Cases
No. Sample Input Sample Output
`1`
`79010089860550`
`Enter the number of students: Enter the grade for student 1: Enter the grade for student 2: Enter the grade for student 3: Enter the grade for student 4: Enter the grade for student 5: Enter the grade for student 6: Enter the grade for student 7:    *                                                       *      *      *                                  *                    *      *     0-9   10-19  20-29  30-39  40-49  50-59  60-69  70-79  80-89  90-100`
`2`
`88845894510009890`
`Enter the number of students: Enter the grade for student 1: Enter the grade for student 2: Enter the grade for student 3: Enter the grade for student 4: Enter the grade for student 5: Enter the grade for student 6: Enter the grade for student 7: Enter the grade for student 8:                                                                   *                                  *                           *      *      *                           *                           *      *     0-9   10-19  20-29  30-39  40-49  50-59  60-69  70-79  80-89  90-100`
`3`
`1100`
`Enter the number of students: Enter the grade for student 1:                                                                   *     0-9   10-19  20-29  30-39  40-49  50-59  60-69  70-79  80-89  90-100`
`4`
`0`
`Enter the number of students:   0-9   10-19  20-29  30-39  40-49  50-59  60-69  70-79  80-89  90-100`

### Methods

#### Odd or Even (Method)

Write a `boolean` method called `isOdd(int number)` that returns `true` if the given `int` `number` is an odd number. The signature of the method is:

`  public static boolean isOdd(int number)`

Also write the `main()` method that prompts user for an `int` `number`, and prints the result.

##### Test Cases
No. Sample Input Sample Output
`1`
`9`
`Enter a number: 9 is an odd number`
`2`
`-9`
`Enter a number: -9 is an odd number`
`3`
`0`
`Enter a number: 0 is an even number `

#### Magic Number (Method)

Write a `boolean` method called `isMagic(int number)` that returns `true` if the given `number` (a positive `int`) contains the digit 8, e.g., 18, 82, 1688. The signature of the method is:

`  public static boolean isMagic(int number);`

Also write the `main()` method that prompts user for a `number`, and prints the result.

##### Test Cases
No. Sample Input Sample Output
`1`
`18`
`Enter a positive integer: 	18 is a magic number`
`2`
`7654321`
`Enter a positive integer: 7654321 is not a magic number`
`3`
`8`
`Enter a positive integer: 8 is a magic number`
`4`
`1`
`Enter a positive integer: 1 is not a magic number`
`5`
`168899`
`Enter a positive integer: 168899 is a magic number `
##### Hints

You could either convert the `int` to a `String` and check each individual `char`; or use modulus-divide-10 to extract each individual digit of the `int`.

#### int array methods (Array & Method)

Write the following methods that take an `int` array as its argument:

```   public static void print(int[] array);      // print [x1, x2, ..., xn]
public static int min(int[] array);         // Returns the minimum
public static int max(int[] array);         // Returns the maximum
public static int sum(int[] array);         // Returns the sum
public static double average(int[] array);  // Returns the average in double
public static boolean isEmpty(int[] array); // Returns true if array's length is 0```

Also write the `main()` method that prompts user for the size of an `int` array, followed by the values; and calls these methods as shown in the sample output.

##### Test Cases
No. Sample Input Sample Output
`1`
`58 6 1 8 5`
`Enter the number of items: Enter the value of all items (separated by space): The values are: [8, 6, 1, 8, 5]The min is: 1The max is: 8The sum is: 28The average (rounded to 2 decimal places) is: 5.60This array is not empty`
`2`
`387 54 61`
`Enter the number of items: Enter the value of all items (separated by space): The values are: [87, 54, 61]The min is: 54The max is: 87The sum is: 202The average (rounded to 2 decimal places) is: 67.33This array is not empty`
`3`
`155`
`Enterh the number of items: Enter the value of all items (separated by space): The values are: [55]The min is: 55The max is: 55The sum is: 55The average (rounded to 2 decimal places) is: 55.00This array is not empty `

#### Search an Array (Array & Method)

Write a method called `search()`, which takes an array of `int` and an `int`; and returns the array index if the array contains the given `int`; or -1 otherwise. The method's signature is as follows:

`public static int search(int[] array, int key);`

Also write the `main()` method that prompts user for the size of an `int` array, followed by its values and a search key; and calls the method as shown in the sample output.

##### Test Cases
No. Sample Input Sample Output
`1`
`56 1 8 2 48`
`Enter the number of items: Enter the value of all items (separated by space): Enter the search key: 8 is found with index 2`
`2`
`48 2 6 19`
`Enter the number of items: Enter the value of all items (separated by space): Enter the search key: 9 is not found`
`3`
`198`
`Enter the number of items: Enter the value of all items (separated by space): Enter the search key: 8 is not found`
`4`
`09`
`Enter the number of items: Enter the search key: 9 is not found `

#### Reverse an Array (Array & Method)

Write a method called `reverse(int[] array)` to reverse the contents of the given array; and a method called `print(int[] array)` to print the array. The signatures are:

```  public static void reverse(int[] array);  // Reverse the contents of the given int array, in place
public static void print(int[] array);    // Print  [x1, x2, ..., xN]```

Also write the `main()` method that prompts user for the size of an `int` array, followed by the values; and calls these methods as shown in the sample output.

##### Test Cases
No. Sample Input Sample Output
`1`
`51 2 3 4 5`
`Enter the number of items: Enter the value of all items (separated by space): The original array is: [1, 2, 3, 4, 5]The reverse is: [5, 4, 3, 2, 1]`
`2`
`387 54 61`
`Enter the number of items: Enter the value of all items (separated by space): The original array is: [87, 54, 61]The reverse is: [61, 54, 87]`
`3`
`155`
`Enter the number of items: Enter the value of all items (separated by space): The original array is: [55]The reverse is: [55]`
`4`
`0`
`Enter the number of items: The original array is: []The reverse is: [] `