Lab 5 (Year 3 Sem 1)

Lab 5 is the sixth lab in semester 1 of year 3, and the sixth lab in the total of year 3. It is a lab for methods, and is considered to be easy.

Description
No description was provided for this lab.

Unlocked after completion

 * OCD (Score at least 60% for Lab 5: Methods)
 * The Black Box (Score at least 80% for Lab 5: Methods)

Question
Write a method with the following header to return the minimum integer:

public static int getMin(int n1, int n2, int n3)

Write a program named Minimum that prompts the user to enter three integers and invokes the getMin method to return the minimum integer.

Sample Output:

Enter three integers: 87 54 23 The minimum integer is 23

Solution
You can either use conditionals, or utilise the built in Math.min function.

Question
A pentagonal number is defined as n(3n–1)/2 for n = 1, 2,. . ., and so on. Therefore, the first few numbers are 1, 5, 12, 22,. . . . Write a method with the following header that returns the nth pentagonal number:

public static int getPentagonalNumber(int n)

Write a program named PentagonalNumber that uses this method to find a list of pentagonal numbers based on a user input N.

Display 7 numbers per line with 8 character space width for each number.

Sample Output: Enter N: 20 The first 20 pentagonal numbers are 1      5       12      22      35      51      70      92      117     145     176     210     247     287     330     376     425     477     532     590

Solution
Use the formula given to implement getPentagonalNumber, and you can use printf (for fixed width) along with a counter to track how many pentagonal numbers have been outputted so far. Remember to print a newline every 7 numbers.

Question
Develop a method public static boolean isPrime(int n) to determine whether a number is prime. Write a program named Prime that uses this method to find the first N prime numbers based on user input N. You may assume that N <= 1000. Display 10 numbers per line with a 5 character space width for each number.

Sample Output: Enter N: 50 The first 50 prime numbers are 2   3    5    7    11   13   17   19   23   29   31   37   41   43   47   53   59   61   67   71   73   79   83   89   97   101  103  107  109  113  127  131  137  139  149  151  157  163  167  173  179  181  191  193  197  199  211  223  227  229

Solution
Testing for primality is trivial and left as an exercise to the reader. Like before, use a printf for fixed width printing and a counter to keep track of how many primes have been printed so far, and print a newline when needed. If you see more newlines being printed than needed, you should check where you are putting the newline printing code.