Java Programming Tutorial

Java Programming Tutorial

Credits: Practice problems taken from below Site.
http://www.ntu.edu.sg/home/ehchua/programming/java/j2a_basicsexercises.html#zz-5

Exercises on Java Basics

You need to do these exercises by yourself. Please don’t ask me for solutions!

1.  Writing Good Programs

The only way to learn programming is program, program and program. Learning programming is like learning cycling, swimming or any other sports. You can’t learn by watching or reading books. Start to program immediately. (On the other hands, to improve your programming, you need to read many books and study how the masters program.)

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.

Pratice problems taken from:

Pay particular attention to:

  1. Coding Style:
    • Read “Java Code Convention” (@ http://www.oracle.com/technetwork/java/codeconvtoc-136057.html or google “Java Code Convention”).
    • Follow the Java Naming Conventions for variables, methods, and classes STRICTLY. Use camel-case for names. Variable and method names begin with lowercase, while class names begin with uppercase. Use nouns for variables (e.g., radius) and class names (e.g., Circle). Use verbs for methods (e.g., getArea(), isEmpty()).
    • Use Meaningful Names: Do not use names like a, b, c, d, x, x1, x2, and x1688. Avoid single-alphabet names like i, j, k. They are easy to type, but usually meaningless. Use single-alphabet names only when their meaning is clear, e.g., x, y, z for co-ordinates and i for array index. Use meaningful names like row and col (instead of x and y, i and j, x1 and x2),numStudents, maxGrade, size, and upperbound. Differentiate between singular and plural nouns (e.g., use books for an array of books, and book for each item).
    • Use consistent indentation and coding style. Many IDEs (such as Eclipse/NetBeans) can re-format your source codes with a click.
  2. Program Documentation: Comment! Comment! and more Comment!

2.  Exercises on Flow Controls

2.1  Exercises on Conditional (Decision)

Exercise CheckPassFail (if-else): Write a program called CheckPassFail which prints “PASS” if the int variable “mark” is more than or equal to 50; or prints “FAIL” otherwise. The program shall always print “DONE” before exiting.

Hints:

Take note of the source-code indentation!!! Whenever you open a block with '{', indent all the statements inside the block by 3 or 4 spaces. When the block ends, un-indent the closing '}'to align with the opening statement.
Exercise CheckOddEven (if-else): Write a program called CheckOddEven which prints “Odd Number” if the int variable “number” is odd, or “Even Number” otherwise. The program shall always print “BYE!” before exiting.

Hints: n is an even number if (n % 2) is 0; otherwise, it is an odd number.

Exercise PrintNumberInWord (nested-if, switch-case): Write a program called PrintNumberInWord which prints “ONE“, “TWO“,… , “NINE“, “OTHER” if the int variable “number” is 1, 2,… , 9, or other, respectively. Use (a) a “nested-if” statement; (b) a “switch-case” statement.

Hints:

Exercise PrintDayInWord (nested-if, switch-case): Write a program called PrintDayInWord which prints “Sunday”, “Monday”, … “Saturday” if the int variable “day” is 0, 1, …, 6, respectively.  Otherwise, it shall print “Not a valid day”. Use (a) a “nested-if” statement; (b) a “switch-case” statement.

2.2  Exercises on Loop (Iteration)

Exercise SumAndAverage (Loop): Write a program called SumAndAverage to produce the sum of 1, 2, 3, …, to 100. Also compute and display the average. The output shall look like:

Hints:

Try:

  1. Modify the program to use a “while-do” loop instead of “for” loop.
  2. Modify the program to use a “do-while” loop.
  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.
  5. Modify the program to sum only the odd numbers from 1 to 100, and compute the average. (HINTS: n is an odd number if n % 2 is not 0.)
  6. Modify the program to sum those numbers from 1 to 100 that is divisible by 7, and compute the average.
  7. 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.

Exercise Product1ToN (Loop): Write a program called Product1ToN to compute the product of integers 1 to 10 (i.e., 1×2×3×…×10). Try computing the product from 1 to 11, 1 to 12, 1 to 13 and 1 to 14. Write down the product obtained and explain the results.

Hints: Declare an int variable called product (to accumulate the product) and initialize to 1.

Try: 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.

Try: Repeat the above, but use long to store the product.  Compare the products obtained.

Hints: Product of 1 to 13 (=6227020800) is outside the range of int [-2147483648, 2147483647], but within the range of long. Take note that computer programs may not produce the correct answer even though everything seems correct!
Exercise HarmonicSum (Loop): Write a program called HarmonicSum to compute the sum of a harmonic series, as shown below, where n=50000. The program shall compute the sum from left-to-right as well as from the right-to-left. Obtain the difference between these two sums and explain the difference. Which sum is more accurate?

ExerciseBasics_HarmonicSum.pngHints:

Exercise ComputePI (Loop & Condition): Write a program called ComputePI to compute the value of π, using the following series expansion. You have to decide on the termination criterion used in the computation (such as the number of terms used or the magnitude of an additional term). Is this series suitable for computing π?

ExerciseBasics_ComputePI.pngJDK maintains the value of π in a double constant called Math.PI. Compare the values obtained and the Math.PI, in percents of Math.PI.

Hints: Add to sum if the denominator modulus 4 is 1, and subtract from sum if it is 3.

Try maxDenominator of 100000, 1000000 and comment on the value of PI computed.

Alternatively, you can use the term number as the loop index:

Exercise CozaLozaWoza (Loop & Condition): Write a program called CozaLozaWoza which prints the numbers 1 to 110, 11 numbers per line. The program shall print “Coza” in place of the numbers which are multiples of 3, “Loza” for multiples of 5, “Woza” for multiples of 7, “CozaLoza” for multiples of 3 and 5, and so on. The output shall look like:

Hints:

A better solution is to use a boolean flag to keep track of whether the number has been processed, as follows:

Exercise Fibonacci (Loop): Write a program called Fibonacci to display the first 20 Fibonacci numbers F(n), where F(n)=F(n–1)+F(n–2) and F(1)=F(2)=1. Also compute their average. The output shall look like:

Hints:

Exercise Tribonacci (Loop): 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.
Exercise ExtractDigits (Loop): 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: Use n % 10 to extract the least-significant digit; and n = n / 10 to discard the least-significant digit.

2.3  Exercises on Nested-Loop

Exercise SquareBoard (nested-loop): Write a program called SquareBoard that displays the following n×n (n=5) pattern using two nested for-loops.

Your program should use only two output statements, one EACH of the followings:

Hints:

Notes: The code pattern for printing 2D patterns using nested loop is:

Exercise CheckerBoard (nested-loop): Write a program called CheckerBoard that displays the following n×n (n=7) checkerboard pattern using two nested for-loops.

Your program should use only three output statements, one EACH of the followings:

Hints:

Exercise TimeTable (nested-loop): Write a program called TimeTable to produce the multiplication table of 1 to 9 as shown using two nested for-loops:

Modify the program to print the multiplication table of 1 to 12. (Hints: use printf() to format the numbers.)
Exercise PrintPattern (nested-loop): Print each of the followings patterns using nested loops.

Hints: On the main diagonal, row = col. On the opposite diagonal, row + col = size + 1, where row and col begin from 1.

3.  Debugging/Tracing Programs using a Graphic Debugger

Exercise (Using a graphic debugger): The following program computes and prints the factorial of n (=1*2*3*...*n). The program, however, has a logical error and produce a wrong answer for n=20 (“The Factorial of 20 is -2102132736” – negative?!). 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).

4.  Exercises on Keyboard and File Input

Exercise KeyboardScanner (Keyboard Input): Write a program called KeyboardScanner to prompt user for an int, a double, and a String. The output shall look like (the inputs are shown in bold):

Hints:

Exercise FileScanner (File Input): Write a program called FileScanner to read an int, a double, and a String form a text file called “in.txt“, and produce the following output:

You need to create a text file called “in.txt” (in Eclipse, right-click on the “project” ⇒ “New” ⇒ “File”) with the following contents:

Ignore the Exception Handling codes for the time being. They will be covered in due course.
Exercise CircleComputation (User Input): Write a program called CircleComputation, which prompts user for a radius (in double) and compute the area and circumference of the circle rounded to 2 decimal places. The output shall look like:

Hints: π is kept in a constant called Math.PI.
Exercise CircleComputation (User Input & Sentinel Value): Modify the above exercise. The program shall repeatedly prompt for the radius, until the user enters -1. For example,

Hints: To repeat until input is -1 (called sentinel value), use the following pattern:

5.  Exercises on String and char Operations

Exercise ReverseString: Write a program called ReverseString, which prompts user for a String, and prints the reverse of the String. The output shall look like:

Hints:

For a String called inStr, you can use inStr.length() to get the length of the String; and inStr.charAt(index) to retrieve the char at the index position, where index begins with 0.
Exercise CheckVowelsDigits: Write a program called CheckVowelsDigits, 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 (with 2 decimal digits).  For example,

Hints:

  • To check if a char c is a digit, you can use boolean expression (c >= '0' && c <= '9'); or use built-in boolean function Character.isDigit(c).
  • You could use in.next().toLowerCase() to convert the input String to lowercase reduce the number of cases.
  • To print a % using printf(), you need to use %%. This is because % has a special meaning in printf(), e.g., %d and %f.

Exercise PhoneKeyPad: On your phone 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. Use a nested-if (or switch-case) in this exercise.

Hints:

  • You can use in.next().toLowerCase() to read a String and convert it to lowercase to reduce your cases.
  • In switch, you can handle multiple cases, e.g.,

Exercise TestPalindromicWord: 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 TestPalindromicWord, that prompts user for a word and prints “"xxx" is|is not a palindrome“.

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 test palindromic phrase.

Hints: Maintain two indexes, forwardIndex and backwardIndex, used to scan the phrase forward and backward. You can check if a char c is a letter either using built-in boolean functionCharacter.isLetter(c); or boolean expression (c >= 'a' && c <= 'z'). Skip the index if it does not contain a letter.

Exercise Bin2Dec: Write a program called Bin2Dec to convert an input binary string into its equivalent decimal number. Your output shall look like:

Hints: For a n-bit binary number bn-1bn-2...b1b0, bi∈{0,1}, the equivalent decimal number is bn-1×2n-1+bn-2×2n-2+ ...+b1×21+b0×20.

You can use JDK method Math.pow(x, y) to compute the x raises to the power of y. This method takes two doubles as argument and returns a double. You have to cast the result back toint.

To convert a char c (of digit '0' to '9') to int (0 to 9), simply subtract by char '0', e.g., '5'-'0' gives int 5.

NOTES: You can use Scanner‘s nextInt(int radix) to read an int in the desired radix. Try reading a binary number (radix of 2) and print its decimal equivalent.
Exercise Hex2Dec: Write a program called Hex2Dec to convert an input hexadecimal string into its equivalent decimal number. Your output shall look like:

Hints:

For a n-digit hexadecimal number hn-1hn-2...h1h0, hi∈{0,…,9,A,…,F}, the equivalent decimal number is hn-1×16n-1+hn-2×16n-2+ ...+h1×161+h0×160.

You need to transform char '0' to '9' to int 0-9; and char 'a' to 'f' (or 'A' to 'F') to int 10-15. However, you do not need a big nested-if statement of 16 cases (or 22 considering the upper and lower letters).  Extract the individual character from the hexadecimal string, says c. If char c is between '0' to '9', you can get the integer offset via c-'0'.  If c is between 'a' to 'f'or 'A' to 'F', the integer offset is c-'a'+10 or c-'A'+10.

Exercise Oct2Dec: Write a program called Oct2Dec to convert an input Octal string into its equivalent decimal number.
Exercise Radix2Dec: Write a program called Radix2Dec to convert an input string of any radix into its equivalent decimal number.

6.  Exercises on Array

Exercise GradesAverage (Array): Write a program called GradesAverage, which prompts user for the number of students, reads it from the keyboard, and saves it in an int variable called numStudents. It then prompts user for the grades of each of the students and saves them in an int array called grades.  Your program shall check that the grade is between 0 and 100. A sample session is as follow:

Exercise Hex2Bin (Array for Table Lookup): Write a program called Hex2Bin to convert a hexadecimal string into its equivalent binary string. The output shall look like:

Hints: Use an array of 16 binary Strings corresponding to hexadecimal number '0' to 'F' (or 'f'), as follows:

7.  Exercises on Method

Exercise (Method): Write a boolean method called isOdd() in a class called OddTest, which takes an int as input and returns true if the it is odd. The signature of the method is as follows:

Also write the main() method that prompts user for a number, and prints “ODD” or “EVEN”. You should test for negative input.
Exercise (Method): Write a boolean method called hasEight(), which takes an int as input and returns true if the number contains the digit 8 (e.g., 18, 808). The signature of the method is as follows:

Write a program called MagicSum, which prompts user for numbers, 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: To repeat until input is -1 (called sentinel value):

Hints: You can either convert the int to String and use the String‘s charAt() to inspect each char; or repeatably use n%10 and n=n/10 to extract each digit (in int).
Exercise (Array and Method): Write a method called printArray(), which takes an int array and print its contents in the form of {a1, a2, ..., an}. Take note that there is no comma after the last element. The method’s signature is as follows:

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 another version for double[], e.g.,

The above is known as method overloading, where the same method name can have many versions, differentiated by its parameter list.
Exercise (Array and Method): Write a method called arrayToString(), which takes an int array and return a String in the form of {a1, a2, ..., an}. Take note that there is no comma after the last element. The method’s signature is as follows:

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 Arrays.toString(). You could study its source code.
Exercise (Array and Method): Write a boolean method called contains(), which takes an array of int and an int; and returns true if the array contains the given int. The method’s signature is as follows:

Also write a test driver to test this method.
Exercise (Array and 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:

Also write a test driver to test this method.
Exercise (Array and Method): Write a boolean method called equals(), which takes two arrays of int and returns true if the two arrays are exactly the same (i.e., same length and same contents). The method’s signature is as follows:

Also write a test driver to test this method.
Exercise (Array and Method): Write a boolean method called copyOf(), which an int Array and returns a copy of the given array. The method’s signature is as follows:

Also write a test driver to test this method.

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.

NOTES: This is similar to the built-in function Arrays.copyOf().
Exercise (Array and Method): Write a method called reverse(), which takes an array of int and reverse its contents. For example, the reverse of {1,2,3,4} is {4,3,2,1}. The method’s signature is as follows:

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“).

Also write a test driver to test this method.

Hint: You need to use a temp location (an int) to swap the first element with the last element, and so on.
Exercise (Array and Method): Write a method called swap(), which takes two arrays of int and swap their contents if they have the same length. It shall return true if the contents are successfully swapped. The method’s signature is as follows:

Also write a test driver to test this method.

Hint: You need to use a temp location (an int) to swap the corresponding elements of the two arrays.
Exercise GradesStatistics (Method): Write a program called GradesStatistics, which reads in n grades (of int between 0 and 100, inclusive) and displays the average, minimum,maximum, median and standard deviation. Display the floating-point values upto 2 decimal places.  Your output shall look like:

The formula for calculating standard deviation is:

ExerciseBasics_GradesAverage.pngHints:

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.
Exercise GradesHistogram (Method): Write a program called GradesHistogram, which reads in n grades (as in the previous exercise), and displays the horizontal and vertical histograms. For example:

Hints:

  • Declare a 10-element int arrays called bins, to maintain the counts for [0,9], [10,19], …, [90,100]. Take note that the bins‘s index is mark/10, except mark of 100.
  • Write the codes to print the star first. Test it. Then print the labels.
  • To print the horizontal histogram, use a nested loop:
  • To print the vertical histogram, you need to find the maximum bin count (called maxBinCount) and use a nested loop:

Exercise (Array and Method): Write a program called PrintChart that prompts the user to input n non-negative integers and draws the corresponding horizontal bar chart. Your program shall use an int array of length n; and comprise methods readInput() and printChart(). A sample session is as follows:

8.  Exercises on Command-line Arguments

Exercise Arithmetic (Command-line arguments): Write a program called Arithmetic that takes three command-line arguments: two integers followed by an arithmetic operator (+, -, * or /). The program shall perform the corresponding operation on the two integers and print the result. For example:

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,

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??
Exercise SumDigits (Command-line arguments): Write a program called SumDigits to sum up the individual digits of a positive integer, given in the command line. The output shall look like:

9.  More (Difficult) Exercises

Exercise (JDK Source Code): Extract the source code of the class Math from the JDK source code (“$JAVA_HOME” ⇒ “src.zip” ⇒ “Math.java” under folder “java.lang“). Study how constants such as E and PI are defined. Also study how methods such as abs(), max(), min(), toDegree(), etc, are written.
Exercise Matrix: Similar to Math class, write a Matrix library that supports matrix operations (such as addition, subtraction, multiplication) via 2D arrays. The operations shall support bothdoubles and ints. Also write a test class to exercise all the operations programmed.

Hints:

Exercise PrintAnimalPattern (Special Characters and Escape Sequences): Write a program called PrintAnimalPattern, which uses println() to produce this pattern:

Hints:

  • 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.
  • Double-quote (") and black-slash (\) require escape sign inside a String. Single quote (') does not require escape sign.

Try: Print the same pattern using printf(). (Hints: Need to use %% to print a % in printf() because % is the suffix for format specifier.)
Exercise PrintPatterns: Write a method to print each of the followings patterns using nested loops in a class called PrintPatterns. The program shall prompt user for the sizde of the pattern. The signatures of the methods are:

Exercise PrintTriangles: Write a method to print each of the following patterns using nested-loops in a class called PrintTriangles. The program shall prompt user for the numRows. The signatures of the methods are:

Exercise TrigonometricSeries: Write a method to compute sin(x) and cos(x) using the following series expansion, in a class called TrigonometricSeries. The signatures of the methods are:

ExerciseBasics_TrigonometricSeries.pngCompare the values computed using the series with the JDK methods Math.sin(), Math.cos() 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:

ExerciseBasics_TrigonometricSeriesHint.png
Exercise Exponential Series: Write a method to compute e and exp(x) using the following series expansion, in a class called TrigonometricSeries. The signatures of the methods are:

ExerciseBasics_ExponentialSeriesHint.png
Exercise SpecialSeries: Write a method to compute the sum of the series in a class called SpecialSeries. The signature of the method is:

ExerciseBasics_Series.png
Exercise FibonacciInt (Overflow) : Write a program called FibonacciInt to list all the Fibonacci numbers, which can be expressed as an int (i.e., 32-bit signed integer in the range of [-2147483648, 2147483647]). The output shall look like:

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:

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-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 room for the next Fibonacci number).

Write a similar program for Tribonacci numbers.
Exercise FactorialInt (Overflow): Write a program called Factorial1to10, to compute the factorial of n, for 1≤n≤10. Your output shall look like:

Modify your program (called FactorialInt), to list all the factorials, that can be expressed as an int (i.e., 32-bit signed integer in the range of [-2147483648, 2147483647]). Your output shall look like:

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:

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 room for the next number.

Try: Modify your program again (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 calledLong.MAX_VALUE.
Exercise Fibonacci (Overflow): Write a program called FibonacciInt to list all the Fibonacci numbers, which can be expressed as an int (i.e., 32-bit signed integer in the range of[-2147483648, 2147483647]).  The output shall look like:

Hints: The maximum 32-bit int is kept in constant Integer.MAX_VALUE. You cannot use 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 room for the next number.

Try: Write a similar program for Tribonacci numbers.
Exercise NumberConversion: Write a method call toRadix() which converts a positive integer from one radix into another. The method has the following header:

Write a program called NumberConversion, which prompts the user for an input number, an input radix, and an output radix, and display the converted number. The output shall look like:

Exercise 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:

Hints: Use Math.random() to produce a random number in double between 0.0 and (less than) 1.0. To produce an int between 0 and 99, use:

Exercise 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:

  • Set up a boolean array to indicate the positions of the word that have been guessed correctly.
  • 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.
  • Try retrieving the word to be guessed from a text file (or a dictionary) randomly.

Exercise 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.

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.
    1700- 1800- 1900- 2000- 2100- 2200- 2300- 2400-
    4 2 0 6 4 2 0 6

    Take note that the entries 4, 2, 0, 6 repeat.

  2. Add to the last two digit of the year.
  3. Add to “the last two digit of the year divide by 4, truncate the fractional part”.
  4. Add to the number obtained from the following month table:
    Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
    Non-Leap Year 0 3 3 6 1 4 6 2 5 0 3 5
    Leap Year 6 2 same as above
  5. Add to the day.
  6. The sum modulus 7 gives the day of the week, where 0 for SUN, 1 for MON, …, 6 for SAT.

For example: 2012, Feb, 17

The skeleton of the program is as follows:

You can compare the day obtained with the Java’s Calendar class as follows:

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.

10.  Exercises on Recursion

In programming, a recursive function calls itself. The classical example is factorial(n), which can be defined recursively as n*factorial(n-1). Nonethessless, it is important to take note that a recursive function should have a terminating condition (or base case), in the case of factorial, factorial(0)=1. Hence, the full definition is:

For example, suppose n = 5:

Exercise (Factorial) (Recursive): Write a recursive method called factorial() to compute the factorial of the given integer.

The recursive algorithm is:

Compare your code with the iteractive version of the factorial():

Hints:

Notes:

  • Recursive version is often much shorter.
  • The recursive version uses much more computation and storage resources, and it need to save its states before each successive recursive call.

Exercise (Fibonacci) (Recursive): Write a recursive method to compute the Fibonacci sequence of n, defined as follows:

Compare the recursive version with the iteractive version written earlier.
Exercise (A Running Number Sequence) (Recursive): A special number sequence is defined as follows:

Write a recursive method to compute the length of S(n). Also write an iteractive version.
Exercise (GCD) (Recursive): Write a recursive method called gcd() to compute the greatest common divisor of two given integers.

Exercise (Tower of Hanoi Recursive) (Recursive): [TODO]

11.  Exercises on Algorithms – Sorting and Searching

Efficient sorting and searching are big topics, typically covered in a course called “Data Structures and Algorithms”. There are many searching and sorting algorithms available, with their respective strengths and weaknesses. See Wikipedia “Sorting Algorithms” and “Searching Algorithms” for the algorithms, examples and illustrations.

JDK provides searching and sorting utilities in the Arrays class (in package java.util), such as Arrays.sort() and Arrays.binarySearch() – 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.
Exercise (Linear Search): (Reference: Wikipedia “Linear Search”) Compare each item with the search key in the linear manner. Linear search is applicable to unsorted list.

Exercise (Recursive Binary Search): (Reference: Wikipedia “Binary Search”) Binary search is only applicable to a sorted list.

For example, suppose that we want to search for the item 18 in the list {11 14 16 18 20 25 28 30 34 40 45}:

Write a recursive function called binarySearch() as follows:

Use the following pesudocode implementation:

Also write an overloaded method which uses the above to search the entire array:

Exercise (Bubble Sort): (Reference: Wikipedia “Bubble Sort”) The principle is to scan the elements from left-to-right, and whenever two adjacent elements are out-of-order, they are swapped. Repeat the passes until no swap are needed.

For example, given the list {9 2 4 1 5}:

See Wikipedia “Bubble Sort” for more examples and illustration.

Write a method to sort an int array (in place) with the following signature:

Use the following pesudocode implementation:

Exercise (Selection Sort): (Reference: Wikipedia “Selection Sort”) This algorithm divides the lists into two parts: the left-sublist of items already sorted, and the right-sublist for the remaining items. Initially, the left-sorted-sublist is empty, while the right-unsorted-sublist is the entire list. The algorithm proceeds by finding the smallest (or largest) items from the right-unsorted-sublist, swapping it with the leftmost element of the right-unsorted-sublist, and increase the left-sorted-sublist by one.

For example, given the list {9 6 4 1 5}:

Write a method to sort an int array (in place) with the following signature:

Exercise (Insertion Sort): (Reference: Wikipedia “Insertion Sort”) Similar to the selection sort, but extract the leftmost element from the right-unsorted-sublist, and insert into the correct location of the left-sorted-sublist.

For example, given {9 6 4 1 5 2 7}:

Write a method to sort an int array (in place) with the following signature:

Exercise (Recursive Quick Sort): (Reference: Wikipedia “Quick Sort”) Quicksort is a recursive divide and conqueralgorithm. It divides the list into two sublists – the low elements and the high element, and recursively sort the sublists. The steps are:

  1. Pick an element, called pivot, from the list.
  2. Partitioning: reorder the list such that the samller elements come before the pivot, and the larger elements after the pivot. After the partitioning, the pivot is in its final position.
  3. Recursively apply the above step to the sub-lists.

For example, given {20 11 18 14 15 9 32 5 26}

Write a recursive function called quickSort() as follows:

Hints: See Binary Search.
Exercise (Merge Sort): (Reference: Wikipedia “Merge Sort”) [TODO]
Exercise (Heap Sort): (Reference: Wikipedia “Heap Sort”) [TODO]

12.  Exercises on Algorithms – Number Theory

Exercise (Perfect and Deficient Numbers): A positive integer is called a perfect number if the sum of all its factors (excluding the number itself, i.e., proper divisor) is equal to its value. For example, the number 6 is perfect because its proper divisors are 1, 2, and 3, and 6=1+2+3; but the number 10 is not perfect because its proper divisors are 1, 2, and 5, and 10≠1+2+5.

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 because1+2+3+4+6>12.

Write a method called isPerfect(int posInt) that takes a positive integer, and return true if the number is perfect. Similarly, write a method called isDeficient(int posInt) to check for deficient numbers.

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:

Exercise (Primes): A positive integer is a prime if it is divisible by 1 and itself only. Write a method called isPrime(int posInt) that takes a positive integer and returns true if the number is a prime. Write a program called PrimeList that prompts the user for an upper bound (a positive integer), and lists all the primes less than or equal to it. Also display the percentage of prime (up to 2 decimal places). 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 √n.
Exercise (Prime Factors): Write a method isProductOfPrimeFactors(int posInt) that takes a positive integer, and return true if the product of all its prime factors (excluding 1 and the number itself) is equal to its value. For example, the method returns true for 30 (30=2×3×5) and false for 20 (20≠2×5). You may need to use the isPrime() method in the previous exercise.

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:

Exercise (Greatest Common Divisor): One of the earlier known algorithms is the Euclid algorithm to find the GCD of two integers (developed by the Greek Mathematician Euclid around 300BC). By definition, GCD(a, b) is the greatest factor that divides both a and b. Assume that a and b are positive integers, and a≥b, the Euclid algorithm is based on these two properties:

For example,

The pseudocode for the Euclid algorithm is as follows:

Write a method called gcd() with the following signature:

Your methods shall handle arbitrary values of a and b, and check for validity.

TRY: Write a recursive version called gcdRecursive() to find the GCD.

13.  Final Notes

The only way to learn programming is program, program and program on challenging problems. The problems in this tutorial are certainly NOT challenging. There are tens of thousands of challenging problems available – used in training for various programming contests (such as International Collegiate Programming Contest (ICPC), International Olympiad in Informatics (IOI)). Check out these sites: