Java Basics Exercises - Java Programming Tutorial
Java Basics Exercises - Java Programming Tutorial
[Link] 1/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
9.1 PrintArray (Array)
Hints 9.2 PrintArrayInStars (Array)
n is an even number if (n % 2) is 0; otherwise, it is an odd number. Use == for comparison, e.g., (n % 2) == 0. 9.3 GradesStatistics (Array)
9.4 Hex2Bin (Array for Table Look
/**
* Trying if-else statement and modulus (%) operator. 9.5 Dec2Hex (Array for Table Look
*/ 10. Exercises on Method
public class CheckOddEven { // Save as "[Link]" 10.1 exponent() (method)
public static void main(String[] args) { // Program entry point
10.2 isOdd() (method)
int number = 49; // Set the value of "number" here!
[Link]("The number is " + number); 10.3 hasEight() (method)
if ( ...... ) { 10.4 print() (Array & Method)
[Link]( ...... ); // even number 10.5 arrayToString() (Array & M
} else {
10.6 contains() (Array & Metho
[Link]( ...... ); // odd number
} 10.7 search() (Array & Method)
[Link]( ...... ); 10.8 equals() (Array & Method)
} 10.9 copyOf() (Array & Method)
}
10.10 swap() (Array & Method)
Try number = 0, 1, 88, 99, -1, -2 and verify your results. 10.11 reverse() (Array & Metho
10.12 GradesStatistics (Array &
Again, take note of the source-code indentation! Make it a good habit to ident your code properly, for ease of
10.13 GradesHistogram (Array &
reading your program.
11. Exercises on Command-line Arg
11.1 Arithmetic (Command-Line
1.4 PrintNumberInWord (nested-if, switch-case) 12. More (Difficult) Exercises
12.1 JDK Source Code
Write a program called PrintNumberInWord which prints "ONE", "TWO",... , "NINE", "OTHER" if the int variable
12.2 Matrices (2D Arrays)
"number" is 1, 2,... , 9, or other, respectively. Use (a) a "nested-if" statement; (b) a "switch-case-default"
12.3 PrintAnimalPattern (Spec
statement.
12.4 Print Patterns (nested-loop)
12.5 Print Triangles (nested-loop)
Hints
12.6 Trigonometric Series
/** 12.7 Exponential Series
* Trying nested-if and switch-case statements. 12.8 Special Series
*/
12.9 FactorialInt (Handling Ov
public class PrintNumberInWord { // Save as "[Link]"
public static void main(String[] args) { 12.10 FibonacciInt (Handling O
int number = 5; // Set the value of "number" here! 12.11 Number System Conversion
12.12 NumberGuess
// Using nested-if
12.13 WordGuess
if (number == 1) { // Use == for comparison
[Link]( ...... ); 12.14 DateUtil
} else if ( ...... ) { 13. Exercises on Recursion
...... 13.1 Factorial Recursive
} else if ( ...... ) {
13.2 Fibonacci (Recursive)
......
...... 13.3 Length of a Running Number
...... 13.4 GCD (Recursive)
} else { 13.5 Tower of Hanoi (Recursive)
...... 14. Exercises on Algorithms - Sorti
}
14.1 Linear Search
// Using switch-case-default 14.2 Recursive Binary Search
switch(number) { 14.3 Bubble Sort
case 1: 14.4 Selection Sort
[Link]( ...... ); break; // Don't forget the "break" after each case! 14.5 Insertion Sort
case 2:
14.6 Recursive Quick Sort
[Link]( ...... ); break;
...... 14.7 Merge Sort
...... 14.8 Heap Sort
default: [Link]( ...... ); 15. Exercises on Algorithms - Num
}
15.1 Perfect and Deficient Numbe
}
}
15.2 Prime Numbers
15.3 Prime Factors
Try number = 0, 1, 2, 3, ..., 9, 10 and verify your results. 15.4 Greatest Common Divisor (G
16. Final Notes
1.5 PrintDayInWord (nested-if, switch-case)
Write a program called PrintDayInWord which prints “Sunday”, “Monday”, ... “Saturday” if the int variable
"dayNumber" is 0, 1, ..., 6, respectively. Otherwise, it shall print "Not a valid day". Use (a) a "nested-if" statement; (b) a "switch-case-default"
statement.
[Link] 2/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
Try dayNumber = 0, 1, 2, 3, 4, 5, 6, 7 and verify your results.
Read "Number Systems" section of "Data Representation", and complete the exercises.
It is easy to write programs that work. It is much harder to write programs that not only work but also easy to maintain and understood by others – I call
these good programs. In the real world, writing program is not meaningful. You have to write good programs, so that others can understand and maintain
your programs.
Hints
/**
* Compute the sum and average of running integers from a lowerbound to an upperbound using loop.
*/
public class SumAverageRunningInt { // Save as "[Link]"
public static void main (String[] args) {
// Define variables
int sum = 0; // The accumulated sum, init to 0
double average; // average in double
final int LOWERBOUND = 1;
final int UPPERBOUND = 100;
[Link] 3/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
// Print sum and average
......
}
}
Tr y
1. Modify the program to use a "while-do" loop instead of "for" loop.
int sum = 0;
int number = LOWERBOUND; // declare and init loop index variable
while (number <= UPPERBOUND) { // test
sum += number;
++number; // update
}
int sum = 0;
int number = LOWERBOUND; // declare and init loop index variable
do {
sum += number;
++number; // update
} while (number <= UPPERBOUND); // test
3. What is the difference between "for" and "while-do" loops? What is the difference between "while-do" and "do-while" loops?
4. Modify the program to sum from 111 to 8899, and compute the average. Introduce an int variable called count to count the numbers in the
specified range (to be used in computing the average).
5. Modify the program to find the "sum of the squares" of all the numbers from 1 to 100, i.e. 1*1 + 2*2 + 3*3 + ... + 100*100.
6. Modify the program to produce two sums: sum of odd numbers and sum of even numbers from 1 to 100. Also computer their absolute difference.
HINTS:
// Define variables
int sumOdd = 0; // Accumulating sum of odd numbers
int sumEven = 0; // Accumulating sum of even numbers
int absDiff; // Absolute difference between the two sums
......
// Compute sums
for (int number = ...; ...; ...) {
if (......) {
sumOdd += number;
} else {
sumEven += number;
}
}
// Compute Absolute Difference
if (sumOdd > sumEven) {
absDiff = ......;
} else {
absDiff = ......;
}
// OR use one liner conditional expression
absDiff = (sumOdd > sumEven) ? ...... : ......;
Hints
Declare an int variable called product, initialize to 1, to accumulate the product.
// Define variables
int product = 1; // The accumulated product, init to 1
final int LOWERBOUND = 1;
final int UPPERBOUND = 10;
[Link] 4/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
Tr y
1. Compute the product from 1 to 11, 1 to 12, 1 to 13 and 1 to 14. Write down the product obtained and decide if the results are correct.
HINTS: Factorial of 13 (=6227020800) is outside the range of int [-2147483648, 2147483647]. Take note that computer programs may not
produce the correct result even though the code seems correct!
2. Repeat the above, but use long to store the product. Compare the products obtained with int for N=13 and N=14.
HINTS: With long, you can store factorial of up to 20.
Hints
/**
* Compute the sum of harmonics series from left-to-right and right-to-left.
*/
public class HarmonicSum { // Save as "[Link]"
public static void main (String[] args) {
// Define variables
final int MAX_DENOMINATOR = 50000; // Use a more meaningful name instead of n
double sumL2R = 0.0; // Sum from left-to-right
double sumR2L = 0.0; // Sum from right-to-left
double absDiff; // Absolute difference between the two sums
Hints
Add to sum if the denominator % 4 is 1, and subtract from sum if it is 3.
[Link] 5/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
}
......
Tr y
1. Instead of using maximum denominator as the terminating condition, rewrite your program to use the maximum number of terms (MAX_TERM) as the
terminating condition.
2. JDK maintains the value of π in a built-in double constant called [Link] (=3.141592653589793). Add a statement to compare the values obtained
and the [Link], in percents of [Link], i.e., (piComputed / [Link]) * 100.
Hints
public class CozaLozaWoza { // Save as "[Link]"
public static void main(String[] args) {
final int LOWERBOUND = 1, UPPERBOUND = 110;
for (int number = LOWERBOUND; number <= UPPERBOUND; ++number) {
// number = LOWERBOUND+1, LOWERBOUND+2, ..., UPPERBOUND
// Print "Coza" if number is divisible by 3
if ( ...... ) {
[Link]("Coza");
}
// Print "Loza" if number is divisible by 5
if ( ...... ) {
[Link](.....);
}
// Print "Woza" if number is divisible by 7
......
// Print the number if it is not divisible by 3, 5 and 7 (i.e., it has not been processed above)
if ( ...... ) {
......
}
// After processing the number, print a newline if number is divisible by 11;
// else print a space
if ( ...... ) {
[Link](); // print newline
} else {
[Link]( ...... ); // print a space
}
}
}
}
Notes
1. You cannot use nested-if (if ... else if ... else if ... else) for this problem. It is because the tests are not mutually exclusive. For example, 15 is divisible by
both 3 and 5. Nested-if is only applicable if the tests are mutually exclusive.
2. The tests above looks messy. A better solution is to use a boolean flag to keep track of whether the number has been processed, as follows:
[Link] 6/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
// Print "Coza" if number is divisible by 3
if ( ...... ) {
[Link]( ...... );
printed = true; // processed!
}
// Print "Loza" if number is divisible by 5
if ( ...... ) {
[Link]( ..... );
printed = true; // processed!
}
// Print "Woza" if number is divisible by 7
......
// Print the number if it has not been processed
if (!printed) {
......
}
// After processing the number, print a newline if it is divisible by 11;
// else, print a space
......
}
Hints
/**
* Print first 20 Fibonacci numbers and their average
*/
public class Fibonacci {
public static void main (String[] args) {
int n = 3; // The index n for F(n), starting from n=3, as n=1 and n=2 are pre-defined
int fn; // F(n) to be computed
int fnMinus1 = 1; // F(n-1), init to F(2)
int fnMinus2 = 1; // F(n-2), init to F(1)
int nMax = 20; // maximum n, inclusive
int sum = fnMinus1 + fnMinus2; // Need sum to compute average
double average;
Tr y
1. Tribonacci numbers are a sequence of numbers T(n) similar to Fibonacci numbers, except that a number is formed by adding the three previous
numbers, i.e., T(n)=T(n-1)+T(n-2)+T(n-3), T(1)=T(2)=1, and T(3)=2. Write a program called Tribonacci to produce the first twenty Tribonacci
numbers.
[Link] 7/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
Write a program called ExtractDigits to extract each digit from an int, in the reverse order. For example, if the int is 15423, the output shall be "3 2 4 5
1", with a space separating the digits.
Hints
The coding pattern for extracting individual digits from an integer n is:
Take note that n is destroyed in the process. You may need to clone a copy.
int n = ...;
while (n > 0) {
int digit = n % 10; // Extract the least-significant digit
// Print this digit
......
n = n / 10; // Drop the least-significant digit and repeat the loop
}
Hints
import [Link]; // For keyboard input
/**
* 1. Prompt user for 2 integers
* 2. Read inputs as "int"
* 3. Compute their sum in "int"
* 4. Print the result
*/
public class Add2Integers { // Save as "[Link]"
public static void main (String[] args) {
// Declare variables
int number1, number2, sum;
// Compute sum
sum = ......
// Display result
[Link]("The sum is: " + sum); // Print with newline
}
}
[Link] 8/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
The min is: 2
The max is: 9
Hints
// Declare variables
int number1, number2, number3; // The 3 input integers
int sum, product, min, max; // To compute these
// 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. Repeat 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;
}
// Print results
......
Tr y
1. 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. Use five int variables: number1, number2, ..., number5 to store the inputs.
Hints
// Declare variables
double radius, diameter, circumference, area; // inputs and results - all in double
......
// Compute in "double"
......
Tr y
[Link] 9/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
1. 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. The formulas are:
Take note that you cannot name the variable surface area with a space or surface-area with a dash. Java's naming convention is surfaceArea.
Other languages recommend surface_area with an underscore.
2. 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. The formulas are:
5.4 Swap2Integers
Write a program called Swap2Integers 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. For examples,
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.
First $20,000 0
Next $20,000 10
Next $20,000 20
The remaining 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. For examples,
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;
......
[Link] 10/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
if (taxableIncome <= 20000) { // [0, 20000]
taxPayable = ......;
} else if (taxableIncome <= 40000) { // [20001, 40000]
taxPayable = ......;
} else if (taxableIncome <= 60000) { // [40001, 60000]
taxPayable = ......;
} else { // [60001, ]
taxPayable = ......;
}
// Alternatively, you could use the following nested-if conditions
// but the above follows the table data
//if (taxableIncome > 60000) { // [60001, ]
// ......
//} else if (taxableIncome > 40000) { // [40001, 60000]
// ......
//} else if (taxableIncome > 20000) { // [20001, 40000]
// ......
//} else { // [0, 20000]
// ......
//}
Tr y
Suppose that a 10% tax rebate is announced for the income tax payable, capped at $1,000, modify your program to handle the tax rebate. For example,
suppose that the tax payable is $12,000, the rebate is $1,000, as 10% of $12,000 exceed the cap.
The -1 is known as the sentinel value. (Wiki: In programming, a sentinel value, also referred to as a flag value, trip value, rogue value, signal value, or
dummy data, is a special value which uses its presence as a condition of termination.)
Hints
The coding pattern for handling input with sentinel value is as follows:
// Declare variables
int taxableIncome;
double taxPayable;
......
[Link] 11/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
// Read the next input
[Link]("Enter the taxable income (or -1 to end): $");
taxableIncome = [Link]();
// 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!
}
[Link]("bye!");
Take note that we repeat the input statements inside and outside the loop. Repeating statements is NOT a good programming practice. This is because it is
easy to repeat (Ctrl-C/Ctrl-V), but hard to maintain and synchronize the repeated statements. In this case, we have no better choices!
55 and below 20 17
above 55 to 60 13 13
above 60 to 65 7.5 9
above 65 5 7.5
However, the contribution is subjected to a salary ceiling of $6,000. In other words, if an employee earns $6 ,800, only $6,000 attracts employee's and
employer's contributions, the remaining $800 does not.
Write a program called PensionContributionCalculator that reads the monthly salary and 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. For examples,
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;
......
[Link] 12/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
Hints
// Read the first input to "seed" the while loop
[Link]("Enter the monthly salary (or -1 to end): $");
salary = [Link]();
......
......
Write a program using a loop to continuously input the tax-inclusive price (in 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.
For examples,
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
......
[Link] 13/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
// Read the first input to "seed" the while loop
[Link]("Enter the tax-inclusive price in dollars (or -1 to end): ");
price = [Link]();
Hints
Use the following coding pattern which uses a while-loop with repeated modulus/divide operations to extract and drop the last digit of a positive integer.
// Declare variables
int inNumber; // to be input
int inDigit; // each digit
......
// Extract and drop the "last" digit repeatably 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
}
......
Hints
See "ReverseInt".
Write a program that prompts user for an integer between 0-10 or 90-100. The program shall read the input as int; and repeat until the user enters a
valid input. For examples,
[Link] 14/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
Hints
Use the following coding pattern which uses a do-while loop controlled by a boolean flag to do input validation. We use a do-while instead of while-do
loop as we need to execute the body to prompt and process the input at least once.
// Declare variables
int numberIn; // to be input
boolean isValid; // boolean flag to control the loop
......
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;
......
sum += ......;
}
......
6. Exercises on Nested-Loops
[Link] 15/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
Hints
The code pattern for printing 2D patterns using nested loops is:
Notes
1. You should name the loop indexes row and col, NOT i and j, or x and y, or a and b, which are meaningless.
2. The row and col could start at 1 (and upto size), or start at 0 (and upto size-1). As computer counts from 0, it is probably more efficient to start
from 0. However, since humans counts from 1, it is easier to read if you start from 1.
Tr y
Rewrite the above program using nested while-do loops.
Hints
// Outer loop to print each of the rows
for (int row = 1; row <= size; row++) { // row = 1, 2, 3, ..., size
// Inner loop to print each of the columns of a particular row
for (int col = 1; col <= size; col++) { // col = 1, 2, 3, ..., size
if ((row % 2) == 0) { // row 2, 4, 6, ...
......
}
[Link]( ...... ); // Use print() without newline inside the inner loop
......
}
// Print a newline after printing all the columns
[Link]();
}
[Link] 16/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
6 | 6 12 18 24 30 36 42 48 54 60
7 | 7 14 21 28 35 42 49 56 63 70
8 | 8 16 24 32 40 48 56 64 72 80
9 | 9 18 27 36 45 54 63 72 81 90
10 | 10 20 30 40 50 60 70 80 90 100
Hints
1. Use printf() to format the output, e.g., each cell is %4d.
2. See "Java Basics" article.
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # #
(a) (b) (c) (d)
Hints
1. On the main diagonal, row = col. On the opposite diagonal, row + col = size + 1, where row and col begin from 1.
2. You need to print the leading blanks, in order to push the # to the right. The trailing blanks are optional, which does not affect the pattern.
3. For pattern (a), if (row >= col) print #. Trailing blanks are optional.
4. For pattern (b), if (row + col <= size + 1) print #. Trailing blanks are optional.
5. For pattern (c), if (row >= col) print #; else print blank. Need to print the leading blanks.
6. For pattern (d), if (row + col >= size + 1) print #; else print blank. Need to print the leading blanks.
7. The coding pattern is:
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # #
# # # # # # # # # #
# # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
(a) (b) (c) (d) (e)
Hints
1. On the main diagonal, row = col. On the opposite diagonal, row + col = size + 1, where row and col begin from 1.
[Link] 17/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
2. For pattern (a), if (row == 1 || row == size || col == 1 || col == size) print #; else print blank. Need to print the intermediate
blanks.
3. For pattern (b), if (row == 1 || row == size || row == col) print #; else print blank.
# # # # # ## # # # # # # # # # # # # # # # # #
# # # # # # ## # # # # # # # # # # # # # # # # #
# # # # # # # ## # # # # # # # # # # # # # # # #
# # # # # # # # ## # # # # # # # # # # # # # # #
# # # # # # # # # ## # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # # # #
(a) (b) # # # # # # # # # # # # #
# # # # # # # # # # # # #
# # # # # # # # # # # # #
# # # # # # # # # # # # #
# # # # # # # # # # # #
(c) (d)
Hints
1. For pattern (a):
1 1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2 1
1 2 1 2 3 4 5 6 7 2 1 7 6 5 4 3 2 1
1 2 3 1 2 3 4 5 6 3 2 1 6 5 4 3 2 1
1 2 3 4 1 2 3 4 5 4 3 2 1 5 4 3 2 1
1 2 3 4 5 1 2 3 4 5 4 3 2 1 4 3 2 1
1 2 3 4 5 6 1 2 3 6 5 4 3 2 1 3 2 1
1 2 3 4 5 6 7 1 2 7 6 5 4 3 2 1 2 1
[Link] 18/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2 1 1
(a) (b) (c) (d)
Hints
[TODO]
Use the graphic debugger of Eclipse/NetBeans to debug the program by single-step through the program and tabulating the values of i and factorial
at the statement marked by (*).
You should try out debugging features such as "Breakpoint", "Step Over", "Watch variables", "Run-to-Line", "Resume", "Terminate", among others. (Read
"Eclipse for Java" or "NetBeans for Java" for details).
// Print factorial of n
public class Factorial {
public static void main(String[] args) { // Set an initial breakpoint at this statement
int n = 20;
int factorial = 1;
// n! = 1*2*3...*n
for (int i = 1; i <= n; i++) { // i = 1, 2, 3, ..., n
factorial = factorial * i; // *
}
[Link]("The Factorial of " + n + " is " + factorial);
}
}
Hints
For a String called inStr, you can use [Link]() to get the length of the String; and [Link](idx) to retrieve the char at the idx
position, where idx begins at 0, up to [Link]() - 1.
// Define variables
String inStr; // input String
int inStrLen; // length of the input String
......
[Link] 19/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
Write a program called CountVowelsDigits, which prompts the user for a String, counts the number of vowels (a, e, i, o, u, A, E, I, O, U) and digits (0-9)
contained in the string, and prints the counts and the percentages (rounded to 2 decimal places). For example,
Hints
1. To check if a char c is a digit, you can use boolean expression (c >= '0' && c <= '9'); or use built-in boolean function
[Link](c).
2. You could use [Link]().toLowerCase() to convert the input String to lowercase to reduce the number of cases.
3. To print a % using printf(), you need to use %%. This is because % is a prefix for format specifier in printf(), e.g., %d and %f.
Hints
1. You can use [Link]().toLowerCase() to read a String and convert it to lowercase to reduce your cases.
2. In switch-case, you can handle multiple cases by omitting the break statement, e.g.,
switch (inChar) {
case 'a': case 'b': case 'c': // No break for 'a' and 'b', fall thru 'c'
[Link](2); break;
case 'd': case 'e': case 'f':
......
default:
......
}
Write a program called CaesarCode to cipher the Caesar's code. The program shall prompt user for a plaintext string consisting of mix-case letters only;
compute the ciphertext; and print the ciphertext in uppercase. For example,
Hints
1. Use [Link]().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 Unicode 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.
Write a program called ExchangeCipher that prompts user for a plaintext string consisting of mix-case letters only. You program shall compute the
ciphertext; and print the ciphertext in uppercase. For examples,
[Link] 20/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
Hints
1. Use [Link]().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 phrase that reads the same backward as forward is also called a palindrome, e.g., "Madam, I'm Adam", "A man, a plan, a canal - Panama!" (ignoring
punctuation and capitalization). Modify your program (called TestPalindromicPhrase) to check for palindromic phrase. Use [Link]() to read a
line of input.
Hints
1. Maintain two indexes, forwardIndex (fIdx) and backwardIndex (bIdx), to scan the phrase forward and backward.
2. You can check if a char c is a letter either using built-in boolean function [Link](c); or boolean expression (c >= 'a' && c <=
'z'). Skip the index if it does not contain a letter.
Hints
Use the following coding pattern which involves a boolean flag to check the input string.
// Declare variables
String inStr; // The input string
int inStrLen; // The length of the input string
char inChar; // Each char of the input string
boolean isValid; // "is" or "is not" a valid binary string?
......
isValid = true; // Assume that the input is valid, unless our check fails
for (......) {
inChar = ......;
if (!(inChar == '0' || inChar == '1')) {
isValid = false;
break; // break the loop upon first error, no need to continue for more errors
// If this is not encountered, isValid remains true after the loop.
}
}
if (isValid) {
[Link](......);
} else {
[Link](......);
[Link] 21/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
}
// or using one liner
//[Link](isValid ? ... : ...);
Hints
if (!((inChar >= '0' && inChar <= '9')
|| (inChar >= 'A' && inChar <= 'F')
|| (inChar >= 'a' && inChar <= 'f'))) { // Use positive logic and then reverse
......
}
Hints
See "Code Example".
Hints
See "Code Example".
9. Exercises on Array
[Link] 22/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
Hints
// Declare variables
final int NUM_ITEMS;
int[] items; // Declare array name, to be allocated after NUM_ITEMS is known
......
// Prompt for for the number of items and read the input as "int"
......
NUM_ITEMS = ......
// Prompt and read the items into the "int" array, if array length > 0
if ([Link] > 0) {
......
for (int i = 0; i < [Link]; ++i) { // Read all items
......
}
}
// Print array contents, need to handle first item and subsequent items differently
......
for (int i = 0; i < [Link]; ++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
//[Link]((i == 0) ? ...... : ......);
}
Hints
// Declare variables
final int NUM_ITEMS;
int[] items; // Declare array name, to be allocated after NUM_ITEMS is known
......
......
[Link] 23/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
for (int starNo = 1; starNo <= items[idx]; ++starNo) { // column
[Link]("*");
}
......
}
......
Hints
1. Use an array of 16 Strings containing binary strings corresponding to hexadecimal number 0-9A-F (or a-f), as follows:
Hints
See "Code Example".
Assume that exp is a non-negative integer and base is an integer. Do not use any Math library functions.
Also write the main() method that prompts user for the base and exp; and prints the result. For example,
Hints
[Link] 24/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
......
public class Exponent {
public static void main(String[] args) {
// Declare variables
int exp; // exponent (non-negative integer)
int base; // base (integer)
......
// Prompt and read exponent and base
......
// Print result
[Link](base + " raises to the power of " + exp + " is: " + exponent(base, exp));
}
return product;
}
}
Also write the main() method that prompts user for a number, and prints "ODD" or "EVEN". You should test for negative input. For examples,
Enter a number: 9
9 is an odd number
Enter a number: 8
8 is an even number
Enter a number: -5
-5 is an odd number
Hints
See Notes.
Write a program called MagicSum, which prompts user for integers (or -1 to end), and produce the sum of numbers containing the digit 8. Your program
should use the above methods. A sample output of the program is as follows:
Hints
1. The coding pattern to repeat until input is -1 (called sentinel value) is:
[Link] 25/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
[Link]("Enter a positive integer (or -1 to end): ");
number = [Link]();
2. You can either repeatably use modulus/divide (n%10 and n=n/10) to extract and drop each digit in int; or convert the int to String and use the
String's charAt() to inspect each char.
Also write a test driver to test this method (you should test on empty array, one-element array, and n-element array).
How to handle double[] or float[]? You need to write a overloaded version for double[] and a overloaded version for float[], with the following
signatures:
The above is known as method overloading, where the same method name can have many versions, differentiated by its parameter list.
Hints
1. For the first element, print its value; for subsequent elements, print commas followed by the value.
Also write a test driver to test this method (you should test on empty array, one-element array, and n-element array).
Notes: This is similar to the built-in function [Link](). You could study its source code.
[Link] 26/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
Write another version for copyOf() which takes a second parameter to specify the length of the new array. You should truncate or pad with zero so that
the new array has the required length.
Hints
You need to use a temporary location to swap two storage locations.
Take note that the array passed into the method can be modified by the method (this is called "pass by reference"). On the other hand, primitives passed
into a method cannot be modified. This is because a clone is created and passed into the method instead of the original copy (this is called "pass by
value").
Hints
1. You might use two indexes in the loop, one moving forward and one moving backward to point to the two elements to be swapped.
for (int fIdx = 0, bIdx = [Link] - 1; fIdx < bIdx; ++fIdx, --bIdx) {
// Swap array[fIdx] and array[bIdx]
// Only need to transverse half of the array elements
}
[Link] 27/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
Enter the grade for student 3: 56
Enter the grade for student 4: 53
The grades are: [50, 51, 56, 53]
The average is: 52.50
The median is: 52.00
The minimum is: 50
The maximum is: 56
The standard deviation is: 2.29
Hints:
// Prompt user for the number of students and allocate the global "grades" array.
// Then, prompt user for grade, check for valid grade, and store in "grades".
public static void readGrades() { ....... }
// Print the given int array in the form of [x1, x2, x3,..., xn].
public static void print(int[] array) { ....... }
Take note that besides readGrade() that relies on global variable grades, all the methods are self-contained general utilities that operate on any given
array.
0 - 9: ***
10 - 19: ***
20 - 29:
30 - 39:
40 - 49: *
50 - 59: *****
60 - 69:
[Link] 28/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
70 - 79:
80 - 89: *
90 -100: **
*
*
* * *
* * * *
* * * * * *
0-9 10-19 20-29 30-39 40-49 50-59 60-69 70-79 80-89 90-100
Hints
See "Code Example".
java Arithmetic 3 2 +
3+2=5
java Arithmetic 3 2 -
3-2=1
java Arithmetic 3 2 /
3/2=1
Hints
The method main(String[] args) takes an argument: "an array of String", which is often (but not necessary) named args. This parameter captures the
command-line arguments supplied by the user when the program is invoked. For example, if a user invokes:
The three command-line arguments "12345", "4567" and "+" will be captured in a String array {"12345", "4567", "+"} and passed into the main()
method as the argument args. That is,
switch(theOperator) {
[Link] 29/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
case ('-'): [Link](operand1 - operand2); break;
case ('+'): ......
case ('*'): ......
case ('/'): ......
default:
[Link]("Error: invalid operator!");
}
}
}
Notes:
To provide command-line arguments, use the "cmd" or "terminal" to run your program in the form "java ClassName arg1 arg2 ....".
To provide command-line arguments in Eclipse, right click the source code ⇒ "Run As" ⇒ "Run Configurations..." ⇒ Select "Main" and choose the
proper main class ⇒ Select "Arguments" ⇒ Enter the command-line arguments, e.g., "3 2 +" in "Program Arguments".
To provide command-line arguments in NetBeans, right click the "Project" name ⇒ "Set Configuration" ⇒ "Customize..." ⇒ Select categories "Run" ⇒
Enter the command-line arguments, e.g., "3 2 +" in the "Arguments" box (but make sure you select the proper Main class).
Question: Try "java Arithmetic 2 4 *" (in CMD shell and Eclipse/NetBeans) and explain the result obtained. How to resolve this problem?
In Windows' CMD shell, * is known as a wildcard character, that expands to give the list of file in the directory (called Shell Expansion). For example, "dir
*.java" lists all the file with extension of ".java". You could double-quote the * to prevent shell expansion. Eclipse has a bug in handling this, even * is
double-quoted. NetBeans??
Hints
public class Matrix {
// Method signatures
public static void print(int[][] m);
public static void print(double[][] m);
public static boolean haveSameDimension(int[][] m1, int[][] m2); // Used in add(), subtract()
public static boolean haveSameDimension(double[][] m1, double[][] m2);
public static int[][] add(int[][] m1, int[][] m2);
public static double[][] add(double[][] m1, double[][] m2);
public static int[][] subtract(int[][] m1, int[][] m2);
public static double[][] subtract(double[][] m1, double[][] m2);
public static int[][] multiply(int[][] m1, int[][] m2);
public static double[][] multiply(double[][] m1, double[][] m2);
......
}
'__'
(©©)
/========\/
/ || %% ||
* ||----||
[Link] 30/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
¥¥ ¥¥
"" ""
Hints
1. Use escape sequence \uhhhh where hhhh are four hex digits to display Unicode characters such as ¥ and ©. ¥ is 165 (00A5H) and © is 169 (00A9H) in
both ISO-8859-1 (Latin-1) and Unicode character sets.
2. Double-quote (") and black-slash (\) require escape sequence inside a String. Single quote (') does not require escape sign.
Tr y
1. Print the same pattern using printf(). (Hints: Need to use %% to print a % in printf() because % is the suffix for format specifier.)
# # # # # # # # # # # # #
# # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # #
# # # # # # # # # # # # # # # # # # # # # # #
(a) (b) # # # # # # # # #
# # # # # # #
# # # # #
# # #
#
(c)
1 1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2 1
1 2 1 2 3 4 5 6 7 2 1 7 6 5 4 3 2 1
1 2 3 1 2 3 4 5 6 3 2 1 6 5 4 3 2 1
1 2 3 4 1 2 3 4 5 4 3 2 1 5 4 3 2 1
1 2 3 4 5 1 2 3 4 5 4 3 2 1 4 3 2 1
1 2 3 4 5 6 1 2 3 6 5 4 3 2 1 3 2 1
1 2 3 4 5 6 7 1 2 7 6 5 4 3 2 1 2 1
1 2 3 4 5 6 7 8 1 8 7 6 5 4 3 2 1 1
(d) (e) (f) (g)
1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 1 1 2 3 4 5 6 7 6 5 4 3 2 1
1 2 3 2 1 1 2 3 4 5 6 5 4 3 2 1
1 2 3 4 3 2 1 1 2 3 4 5 4 3 2 1
1 2 3 4 5 4 3 2 1 1 2 3 4 3 2 1
1 2 3 4 5 6 5 4 3 2 1 1 2 3 2 1
1 2 3 4 5 6 7 6 5 4 3 2 1 1 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1
(h) (i)
1 1 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1 2 2 1 1 2 3 4 5 6 7 7 6 5 4 3 2 1
1 2 3 3 2 1 1 2 3 4 5 6 6 5 4 3 2 1
1 2 3 4 4 3 2 1 1 2 3 4 5 5 4 3 2 1
1 2 3 4 5 5 4 3 2 1 1 2 3 4 4 3 2 1
1 2 3 4 5 6 6 5 4 3 2 1 1 2 3 3 2 1
1 2 3 4 5 6 7 7 6 5 4 3 2 1 1 2 2 1
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1 1 1
(j) (k)
1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5
6 7 8 9 0 1 0 9 8 7 6
7 8 9 0 1 2 3 2 1 0 9 8 7
8 9 0 1 2 3 4 5 4 3 2 1 0 9 8
(l)
[Link] 31/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
(a) PowerOf2Triangle
1 1
1 1 1 1
1 2 1 1 2 1
1 3 3 1 1 3 1 3
1 4 6 4 1 1 4 6 4 1
1 5 10 10 5 1 1 5 10 10 5 1
1 6 15 20 15 6 1 1 6 15 20 15 6 1
(b) PascalTriangle1 (c) PascalTriangle2
Compare the values computed using the series with the JDK methods [Link](), [Link]() at x=0, π/6, π/4, π/3, π/2 using various numbers of terms.
Hints
Do not use int to compute the factorial; as factorial of 13 is outside the int range. Avoid generating large numerator and denominator. Use double to
compute the terms as:
[Link] 32/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
The factorial of 1 is 1
The factorial of 2 is 2
...
The factorial of 12 is 479001600
The factorial of 13 is out of range
Hints
The maximum and minimum values of a 32-bit int are kept in constants Integer.MAX_VALUE and Integer.MIN_VALUE, respectively. Try these
statements:
[Link](Integer.MAX_VALUE);
[Link](Integer.MIN_VALUE);
[Link](Integer.MAX_VALUE + 1);
Take note that in the third statement, Java Runtime does not flag out an overflow error, but silently wraps the number around. Hence, you cannot use F(n)
* (n+1) > Integer.MAX_VALUE to check for overflow. Instead, overflow occurs for F(n+1) if (Integer.MAX_VALUE / Factorial(n)) < (n+1), i.e., no
more room for the next number.
Tr y
Modify your program called FactorialLong to list all the factorial that can be expressed as a long (64-bit signed integer). The maximum value for long is
kept in a constant called Long.MAX_VALUE.
F(0) = 1
F(1) = 1
F(2) = 2
...
F(45) = 1836311903
F(46) is out of the range of int
Hints
The maximum and minimum values of a 32-bit int are kept in constants Integer.MAX_VALUE and Integer.MIN_VALUE, respectively. Try these
statements:
[Link](Integer.MAX_VALUE);
[Link](Integer.MIN_VALUE);
[Link](Integer.MAX_VALUE + 1);
Take note that in the third statement, Java Runtime does not flag out an overflow error, but silently wraps the number around. Hence, you cannot use F(n)
= F(n-1) + F(n-2) > Integer.MAX_VALUE to check for overflow. Instead, overflow occurs for F(n) if Integer.MAX_VALUE – F(n-1) < F(n-2) (i.e.,
no more room for the next Fibonacci number).
Tr y
Write a similar program called TribonacciInt for Tribonacci numbers.
public static String toRadix(String in, int inRadix, int outRadix) // The input and output are treated as String.
Write a program called NumberConversion, which prompts the user for an input string, an input radix, and an output radix, and display the converted
number. The output shall look like:
[Link] 33/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
Enter the output radix: 2
"A1B2" in radix 16 is "1010000110110010" in radix 2.
12.12 NumberGuess
Write a program called NumberGuess to play the number guessing game. The program shall generate a random number between 0 and 99. The player
inputs his/her guess, and the program shall response with "Try higher", "Try lower" or "You got it in n trials" accordingly. For example:
java NumberGuess
Key in your guess:
50
Try higher
70
Try lower
65
Try lower
61
You got it in 4 trials!
Hints
Use [Link]() to produce a random number in double between 0.0 (inclusive) and 1.0 (exclusive). To produce an int between 0 and 99, use:
12.13 WordGuess
Write a program called WordGuess to guess a word by trying to guess the individual characters. The word to be guessed shall be provided using the
command-line argument. Your program shall look like:
Hints
1. Set up a boolean array (of the length of the word to be guessed) to indicate the positions of the word that have been guessed correctly.
2. Check the length of the input String to determine whether the player enters a single character or a guessed word. If the player enters a single
character, check it against the word to be guessed, and update the boolean array that keeping the result so far.
Tr y
Try retrieving the word to be guessed from a text file (or a dictionary) randomly.
12.14 DateUtil
Complete the following methods in a class called DateUtil:
boolean isLeapYear(int year): returns true if the given year is a leap year. A year is a leap year if it is divisible by 4 but not by 100, or it is
divisible by 400.
boolean isValidDate(int year, int month, int day): returns true if the given year, month and day constitute a given date. Assume that year
is between 1 and 9999, month is between 1 (Jan) to 12 (Dec) and day shall be between 1 and 28|29|30|31 depending on the month and whether it is a
leap year.
int getDayOfWeek(int year, int month, int day): returns the day of the week, where 0 for SUN, 1 for MON, ..., 6 for SAT, for the given date.
Assume that the date is valid.
String toString(int year, int month, int day): prints the given date in the format "xxxday d mmm yyyy", e.g., "Tuesday 14 Feb 2012".
Assume that the given date is valid.
Hints
To find the day of the week (Reference: Wiki "Determination of the day of the week"):
1. Based on the first two digit of the year, get the number from the following "century" table.
[Link] 34/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
// Test Driver
public static void main(String[] args) {
[Link](isLeapYear(1900)); // false
[Link](isLeapYear(2000)); // true
[Link](isLeapYear(2011)); // false
[Link](isLeapYear(2012)); // true
Notes
You can compare the day obtained with the Java's Calendar class as follows:
[Link] 35/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
// Construct a Calendar instance with the given year, month and day
Calendar cal = new GregorianCalendar(year, month - 1, day); // month is 0-based
// Get the day of the week number: 1 (Sunday) to 7 (Saturday)
int dayNumber = [Link](Calendar.DAY_OF_WEEK);
String[] calendarDays = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
// Print result
[Link]("It is " + calendarDays[dayNumber - 1]);
The calendar we used today is known as Gregorian calendar, which came into effect in October 15, 1582 in some countries and later in other countries. It
replaces the Julian calendar. 10 days were removed from the calendar, i.e., October 4, 1582 (Julian) was followed by October 15, 1582 (Gregorian). The only
difference between the Gregorian and the Julian calendar is the "leap-year rule". In Julian calendar, every four years is a leap year. In Gregorian calendar, a
leap year is a year that is divisible by 4 but not divisible by 100, or it is divisible by 400, i.e., the Gregorian calendar omits century years which are not
divisible by 400. Furthermore, Julian calendar considers the first day of the year as march 25th, instead of January 1st.
This above algorithm work for Gregorian dates only. It is difficult to modify the above algorithm to handle pre-Gregorian dates. A better algorithm is to
find the number of days from a known date.
factorial(n) = 1, for n = 0
factorial(n) = n * factorial(n-1), for all n > 1
// Recursive call
factorial(5) = 5 * factorial(4)
factorial(4) = 4 * factorial(3)
factorial(3) = 3 * factorial(2)
factorial(2) = 2 * factorial(1)
factorial(1) = 1 * factorial(0)
factorial(0) = 1 // Base case
// Unwinding
factorial(1) = 1 * 1 = 1
factorial(2) = 2 * 1 = 2
factorial(3) = 3 * 2 = 6
factorial(4) = 4 * 6 = 24
factorial(5) = 5 * 24 = 120 (DONE)
factorial(n) = 1, if n = 0
factorial(n) = n * factorial(n-1), if n > 0
factorial(n) = 1*2*3*...*n
Hints
Writing recursive function is straight forward. You simply translate the recursive definition into code with return.
[Link] 36/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
Notes
1. Recursive version is often much shorter.
2. The recursive version uses much more computational and storage resources, and it need to save its current states before each successive recursive
call, so as to unwind later.
F(0) = 0
F(1) = 1
F(n) = F(n-1) + F(n-2) for n >= 2
Compare the recursive version with the iterative version written earlier.
Hints
// Translate the recursive definition into code with return statements
public static int fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n-1) + fibonacci(n-2);
}
}
S(1) = 1
S(2) = 12
S(3) = 123
S(4) = 1234
......
S(9) = 123456789 // length is 9
S(10) = 12345678910 // length is 11
S(11) = 1234567891011 // length is 13
S(12) = 123456789101112 // length is 15
......
len(1) = 1
len(n) = len(n-1) + numOfDigits(n)
gcd(a,b) = a, if b = 0
gcd(a,b) = gcd(b, remainder(a,b)), if b > 0
[Link] 37/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
JDK provides searching and sorting utilities in the Arrays class (in package [Link]), such as [Link]() and [Link]() - you
don't have to write your searching and sorting in your production program. These exercises are for academic purpose and for you to gain some
understandings and practices on these algorithms.
Create two indexes: firstIdx and lastIdx , initially pointing at the first and last elements
[11 14 16 18 20 25 28 30 34 40 45]
F M L
Compute middleIdx = (firstIdx + lastIdx) / 2
Compare the key (K) with the middle element (M)
If K = M, return true
else if K < M, set firstIdx = middleIndex
else if K > M, set firstIdx = middleIndex
{11 14 16 18 20 25 28 30 34 40 45}
F M L
Recursively repeat the search between the new firstIndex and lastIndex.
Terminate with not found when firstIndex = lastIndex.
{11 14 16 18 20 25 28 30 34 40 45}
F M L
// Return true if key is found in the array in the range of fromIdx (inclusive) to toIdx (exclusive)
public boolean binarySearch(int[] array, int key, int fromIdx, int toIdx)
Also write an overloaded method which uses the above to search the entire array:
Pass 1:
9 2 4 1 5 -> 2 9 4 1 5
2 9 4 1 5 -> 2 4 9 1 5
2 4 9 1 5 -> 2 4 1 9 5
2 4 1 9 5 -> 2 4 1 5 9 (After Pass 1, the largest item sorted on the right - bubble to the right)
Pass 2:
2 4 1 5 9 -> 2 4 1 5 9
[Link] 38/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
2 4 1 5 9 -> 2 1 4 5 9
2 1 4 5 9 -> 2 1 4 5 9
2 1 4 5 9 -> 2 1 4 5 9 (After Pass 2, the 2 largest items sorted on the right)
Pass 3:
2 1 4 5 9 -> 1 2 4 5 9
1 2 4 5 9 -> 1 2 4 5 9
1 2 4 5 9 -> 1 2 4 5 9
1 2 4 5 9 -> 1 2 4 5 9 (After Pass 3, the 3 largest items sorted on the right)
Pass 4:
1 2 4 5 9 -> 1 2 4 5 9
1 2 4 5 9 -> 1 2 4 5 9
1 2 4 5 9 -> 1 2 4 5 9
1 2 4 5 9 -> 1 2 4 5 9 (After Pass 4, the 4 largest items sorted on the right)
No Swap in Pass 4. Done.
Write a method to sort an int array (in place) with the following signature:
function bubbleSort(array)
n = length(array)
boolean swapped // boolean flag to indicate swapping occurred during a pass
do {
swapped = false // reset for each pass
for (i = 1; i < n; ++i) {
// Swap if this pair is out of order
if array[i-1] > array[i] {
swap( A[i-1], A[i] )
swapped = true // update flag
}
}
n = n - 1 // One item sorted after each pass
} while (swapped) // repeat another pass if swapping occurred, otherwise done
{} {9 6 4 1 5} -> {} {1 6 4 9 5}
{1} {6 4 9 5} -> {1} {4 6 9 5}
{1 4} {6 9 5} -> {1 4} {5 9 6}
{1 4 5} {9 6} -> {1 4 5} {6 9}
{1 4 5 6} {9} -> DONE
{1 4 5 6 9}
Write a method to sort an int array (in place) with the following signature:
{} {9 6 4 1 5 2 7} -> {9} {6 4 1 5 2 7}
{9} {6 4 1 5 2 7} -> {6 9} {4 1 5 2 7}
{6 9} {4 1 5 2 7} -> {4 6 9} {1 5 2 7}
{4 6 9} {1 5 2 7} -> {1 4 6 9} {5 2 7}
{1 4 6 9} {5 2 7} -> {1 4 5 6 9} {2 7}
{1 4 5 6 9} {2 7} -> {1 2 4 5 6 9} {7}
{1 2 4 5 6 9} {7} -> {1 2 4 5 6 7 9} {}
{1 2 4 5 6 7 9} {} -> Done
Write a method to sort an int array (in place) with the following signature:
[Link] 39/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
Select the middle element as the pivot, place the pivot at the end of the list, by swapping with the last element
{20 11 18 14 15 9 32 5 26} -> {20 11 18 14 26 9 32 5} {15}
Partitioning:
Initialize a variable swapPos (underlined), initially pointing to the leftmost element.
Compare each element (in red) with the pivot,
if the element is smaller than the pivot, swap with the element at the swapPos and increase swapPos by 1.
otherwise, do nothing.
{20 11 18 14 26 9 32 5} {15} -> larger, do nothing
{20 11 18 14 26 9 32 5} {15} -> smaller, swap and increment swapPos -> {11 20 18 14 26 9 32 5} {15}
{11 20 18 14 26 9 32 5} {15} -> larger, do nothing
{11 20 18 14 26 9 32 5} {15} -> smaller, swap and increment swapPos -> {11 14 18 20 26 9 32 5} {15}
{11 14 18 20 26 9 32 5} {15} -> larger, do nothing
{11 14 18 20 26 9 32 5} {15} -> smaller, swap and increment swapPos -> {11 14 9 20 26 18 32 5} {15}
{11 14 9 20 26 18 32 5} {15} -> larger, do nothing
{11 14 9 20 26 18 32 5} {15} -> smaller, swap and increment swapPos -> {11 14 9 5 26 18 32 20} {15}
Partitioning done. Swap the pivot.
{11 14 9 5 15 18 32 20 26}
All elements before the pivot are smaller; all elements after the pivot are larger.
Pivot is sorted in the correct position.
Recursively repeat the process for sublists {11 14 9 5} and {18 32 20 26}
// Sort the array in place from the fromIdx (inclusive) to toIdx (exclusive)
public boolean quickSort(int[] array, int fromIdx, int toIdx)
// Sort the entire array
public boolean quickSort(int[] array)
Hints
See Binary Search.
A positive integer is called a deficient number if the sum of all its proper divisors is less than its value. For example, 10 is a deficient number because
1+2+5<10; while 12 is not because 1+2+3+4+6>12.
Write a boolean method called isPerfect(int aPosInt) that takes a positive integer, and return true if the number is perfect. Similarly, write a boolean
method called isDeficient(int aPosInt) to check for deficient numbers.
[Link] 40/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
Using the methods, write a program called PerfectNumberList that prompts user for an upper bound (a positive integer), and lists all the perfect
numbers less than or equal to this upper bound. It shall also list all the numbers that are neither deficient nor perfect. The output shall look like:
Hints
To check if a number n is a prime, the simplest way is try dividing n by 2 to sqrt(n).
Write a program called PerfectPrimeFactorList that prompts user for an upper bound. The program shall display all the numbers (less than or equal to
the upper bound) that meets the above criteria. The output shall look like:
GCD(a, 0) = a
GCD(a, b) = GCD(b, a mod b), where (a mod b) denotes the remainder of a divides by b.
For example,
GCD(15, 5) = GCD(5, 0) = 5
GCD(99,88) = GCD(88,11) = GCD(11,0) = 11
GCD(3456,1233) = GCD(1233,990) = GCD(990,243) = GCD(243,18) = GCD(18,9) = GCD(9,0) = 9
[Link] 41/42
2/3/26, 9:47 AM Java Basics Exercises - Java Programming Tutorial
// after the loop completes, i.e., b is 0, we have GCD(a, 0)
GCD is a
Your methods shall handle arbitrary values of a and b, and check for validity.
Tr y
Write a recursive version called gcdRecursive() to find the GCD.
Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan (ehchua@[Link]) | HOME
[Link] 42/42