These exercises are meant for submission to my online submission system.
Getting Started Exercises
Add Two Integers (Add2Integer.java) (Getting Started)
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 |
5 |
Enter first integer: |
2 |
-5 |
Enter first integer: |
3 |
8 |
Enter first integer: |
4 |
8 |
Enter first integer: |
5 |
-8 |
Enter first integer: |
6 |
0 |
Enter first integer: |
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 class Add2Integers { // Save as "Add2Integers.java" 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: |
2 |
88 |
Enter an integer: |
3 |
0 |
Enter an integer: |
4 |
-1 |
Enter an integer: |
5 |
-4 |
Enter an integer: |
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 |
99 |
Enter 1st integer: |
2 |
99 |
Enter 1st integer: |
3 |
5 |
Enter 1st integer: |
Hints
- Use two
intvariables:number1andnumber2to store the inputs. - 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 |
3 |
Enter 1st integer: |
2 |
44 |
Enter 1st integer: |
3 |
199 |
Enter 1st integer: |
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 |
5 |
Enter 1st integer: |
2 |
-999 |
Enter 1st integer: |
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: |
2 |
6 |
Enter the day number: |
3 |
9 |
Enter the day number: |
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: |
2 |
6 |
Enter a number: |
3 |
-1 |
Enter a number: |
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 |
Enter the length: |
2 |
8 |
Enter the length: |
3 |
1 |
Enter the length: |
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; diameter = 2.0 * radius; circumference = 2.0 * Math.PI * radius;
Test Cases
| No. | Sample Input | Sample Output |
|---|---|---|
1 |
1.2 |
Enter the radius: |
2 |
1 |
Enter the radius: |
3 |
0.12e2 |
Enter the radius: |
4 |
0 |
Enter the radius: |
Hints
- Use
doublevariablesradius,diameter,circumferenceandareato store the input and results. - Use
in.nextDouble()to read adouble. - Use
System.out.printf()with specifier%.2fto print adouble, rounded to 2 decimal places; and%nto print a newline. For example,
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: |
2 |
1 |
Enter the radius: |
3 |
0.12e2 |
Enter the radius: |
4 |
0 |
Enter the radius: |
Hints
- Use
doublevariablesradius,volumeandsurfaceAreato store the input and results. - Use
in.nextDouble()to read adouble. - Use
System.out.printf()with specifier%.2fto print adoublerounded to 2 decimal places; and%nto print a newline. For example,
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 |
1 |
Enter the radius: |
2 |
1.1 |
Enter the radius: |
3 |
3 |
Enter the radius: |
Hints
- Use
doublevariablesradius,height,baseArea,surfaceAreaandvolumeto store the inputs and results. Take note that spaces are not allowed in names. - Use
in.nextDouble()to read adouble. - Use
System.out.printf()with specifier%.2fto print adouble, rounded to 2 decimal places; and%nto print a newline. For example,
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 |
5 |
Enter first integer: |
2 |
9 |
Enter first integer: |
3 |
11 |
Enter first integer: |
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 |
1 |
Enter the lowerbound: |
2 |
1 |
Enter the lowerbound: |
3 |
10 |
Enter the lowerbound: |
4 |
-5 |
Enter the lowerbound: |
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: |
2 |
5 |
Enter an integer: |
3 |
1 |
Enter an integer: |
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: |
2 |
20 |
Enter an integer: |
3 |
1 |
Enter an integer: |
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: $ |
2 |
20001 |
Enter the taxable income: $ |
3 |
25000 |
Enter the taxable income: $ |
4 |
40000 |
Enter the taxable income: $ |
5 |
50000 |
Enter the taxable income: $ |
6 |
60000 |
Enter the taxable income: $ |
7 |
85000 |
Enter the taxable income: $ |
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 |
3000 |
Enter the monthly salary: $ |
2 |
4123 |
Enter the monthly salary: $ |
3 |
4123 |
Enter the monthly salary: $ |
4 |
4123 |
Enter the monthly salary: $ |
5 |
4123 |
Enter the monthly salary: $ |
6 |
4123 |
Enter the monthly salary: $ |
7 |
4123 |
Enter the monthly salary: $ |
8 |
6000 |
Enter the monthly salary: $ |
9 |
8899 |
Enter the monthly salary: $ |
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 |
12345 |
Enter the taxable income (or -1 to end): $ |
2 |
98765 |
Enter the taxable income (or -1 to end): $ |
3 |
-1 |
Enter the taxable income (or -1 to end): $ |
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
......
// Read the next input
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 |
5123 |
Enter the monthly salary (or -1 to end): $ |
2 |
1234 |
Enter the monthly salary (or -1 to end): $ |
3 |
-1 |
Enter the monthly salary (or -1 to end): $ |
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 |
10000 |
Enter sales in dollars (or -1 to end): |
2 |
12345 |
Enter sales in dollars (or -1 to end): |
3 |
0 |
Enter sales in dollars (or -1 to end): |
4 |
-1 |
Enter sales in dollars (or -1 to end): |
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
......
// Read the next input
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 |
107 |
Enter the tax-inclusive price in dollars (or -1 to end): |
2 |
123 |
Enter the tax-inclusive price in dollars (or -1 to end): |
3 |
1234.56 |
Enter the tax-inclusive price in dollars (or -1 to end): |
4 |
-1 |
Enter the tax-inclusive price in dollars (or -1 to end): |
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
......
// Read the next input
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: |
2 |
1000 |
Enter the max denominator: |
3 |
1 |
Enter the max denominator: |
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: |
2 |
1000 |
Enter the maximum denominator: |
3 |
100 |
Enter the maximum denominator: |
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) {
// add into sum
......
} 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: |
2 |
67890 |
Enter a positive integer: |
3 |
1 |
Enter a positive integer: |
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: |
2 |
67890 |
Enter a positive integer: |
3 |
1 |
Enter a positive integer: |
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 |
-1 |
Enter a number between 0-10 or 90-100: |
2 |
-1 |
Enter a number between 0-10 or 90-100: |
3 |
5 |
Enter a number between 0-10 or 90-100: |
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 {
// Prompt and read input
......
// 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 |
35 |
Enter the mark (0-100) for student 1: |
2 |
56 |
Enter the mark (0-100) for student 1: |
3 |
101 |
Enter the mark (0-100) for student 1: |
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: |
2 |
5 |
Enter the size: |
3 |
1 |
Enter the size: |
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: |
2 |
5 |
Enter the size of the table: |
3 |
1 |
Enter the size of the table: |
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: |
2 |
12345 |
Enter a String: |
3 |
a |
Enter a String: |
Hints
- For a
StringcalledinStr, you can useinStr.length()to get the length of theString; andinStr.charAt(index)to retrieve thecharat theindexposition, whereindexbegins with 0. - Use a for-loop to extract each
charof the inputStringin the reverse order, and print the extractedchar. 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: |
2 |
HelloWorld |
Enter a String: |
Hints
- You could use
in.next().toLowerCase()to read an inputStringand convert it into lowercase to reduce the number of cases. - 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: |
2 |
1string2strings3strings |
Enter a String: |
3 |
bcdfghjklmn |
Enter a String: |
Hints
- Use
in.next().toLowerCase()to read an input string and convert it into lowercase to reduce the number of cases. - To check if a
char cis a digit, you can usebooleanexpression(c >= '0' && c <= '9'); or use built-inbooleanfunctionCharacter.isDigit(c). - To print a
%usingprintf(), you need to use%%. This is because%has a special meaning insideprintf(), e.g.,%dand%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: |
2 |
1800flower |
Enter a String: |
3 |
1_2-3@4xyz |
Enter a String: |
4 |
helloworld |
Enter a String: |
Hints
To check if a char c is a digit character '0' to '9', you can use either:
booleanexpression(c >= '0' && c <= '9'); or- built-in
booleanfunctionCharacter.isDigit(c)which returnstrueifcis 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: |
2 |
HELLOWORLD |
Enter a plaintext string: |
3 |
ASecretText |
Enter a plaintext string: |
4 |
AaBbCcXxYyZz |
Enter a plaintext string: |
5 |
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz |
Enter a plaintext string: |
Hints
- Use
in.next().toUpperCase()to read an input string and convert it into uppercase to reduce the number of cases. - 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. - Take note that
char 'A'is represented as code number65andchar 'D'as68. However,'A' + 3 gives 68. This is becausechar + intis implicitly casted toint + intwhich returns anintvalue. To obtain acharvalue, 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: |
2 |
testing |
Enter a plaintext string: |
3 |
ASecretText |
Enter a plaintext string: |
4 |
m |
Enter a plaintext string: |
Hints
- Use
in.next().toUpperCase()to read an input string and convert it into uppercase to reduce the number of cases. - 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: |
2 |
10000011 |
Enter a binary string: |
3 |
0 |
Enter a binary string: |
4 |
1 |
Enter a binary string: |
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: |
2 |
7123 |
Enter an octal string: |
3 |
0 |
Enter an octal string: |
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: |
2 |
RaceCar |
Enter a String: |
3 |
m |
Enter a String: |
4 |
Hello |
Enter a String: |
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 |
5 |
Enter the number of items: |
2 |
2 |
Enter the number of items: |
3 |
1 |
Enter the number of items: |
4 |
0 |
Enter the number of items: |
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 |
Enter the number of items: |
2 |
2 |
Enter the number of items: |
3 |
1 |
Enter the number of items: |
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 |
3 |
Enter the number of students: |
2 |
5 |
Enter the number of students: |
3 |
1 |
Enter the number of students: |
Grades Histogram Bins (Arrays)
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 |
7 |
Enter the number of students: |
2 |
8 |
Enter the number of students: |
3 |
1 |
Enter the number of students: |
4 |
0 |
Enter the number of students: |
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 {
++bins[grades[i]/10];
}
}
// 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]);
}
Grades Histogram Horizontal (Array)
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 |
7 |
Enter the number of students: |
2 |
8 |
Enter the number of students: |
3 |
1 |
Enter the number of students: |
4 |
0 |
Enter the number of students: |
Grades Histogram Vertical (Array)
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 |
7 |
Enter the number of students: |
2 |
8 |
Enter the number of students: |
3 |
1 |
Enter the number of students: |
4 |
0 |
Enter the number of students: |
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: |
2 |
-9 |
Enter a number: |
3 |
0 |
Enter a 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: |
2 |
7654321 |
Enter a positive integer: |
3 |
8 |
Enter a positive integer: |
4 |
1 |
Enter a positive integer: |
5 |
168899 |
Enter a positive integer: |
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 |
5 |
Enter the number of items: |
2 |
3 |
Enter the number of items: |
3 |
1 |
Enter the number of items: |
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 |
5 |
Enter the number of items: |
2 |
4 |
Enter the number of items: |
3 |
1 |
Enter the number of items: |
4 |
0 |
Enter the number of items: |
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 |
5 |
Enter the number of items: |
2 |
3 |
Enter the number of items: |
3 |
1 |
Enter the number of items: |
4 |
0 |
Enter the number of items: |