The aims of these exercises are to:
Practice writing logical tests in Java.
Practice using arrays in Java.
Students should read Weiss Chapter 2 Section 2.4 in preparation for these lab exercises.
Students are not expected to complete every exercise in these lab exercises. Select about 5 examples from each group.
Write a method public static void printArray( int [ ] arr )
to print out the elements of an array in order. You can use any formatting you like to make your printed list clear.
Write a method public static int countZeros( int [ ] arr )
to print out the number of elements in an array (if any) that are equal to 0.
Write a method public static int countNs( int [ ] arr, int n )
to print out the number of elements in an array (if any) that are equal to the parameter n. Change your countZeros
method from the last question so that it simply calls your new
countNs
method. This approach is called using a helper method.
Write a method public static int isIncreasing( int [ ] arr )
which is true only if the elements of the array are increasing. That is, following elements are greater than or equal to previous elements.
If you are not on-line for this lab, then answer the questions given below in your own Java file instead. A sample java file is given here: lab03answers.java. It is recommended that you save your answers in this Java file anyway, so you can use them later for revision.
Given an array of ints, return true if 6 appears as either the first or last element in the array. The array will be length 1 or more.
firstLast6({1, 2, 6}) returns true
firstLast6({6, 1, 2, 3}) returns true
firstLast6({13, 6, 1, 2, 3}) returns false
We'll say that a 1 immediately followed by a 3 in an array is an "unlucky" 1. Return true if the given array contains an unlucky 1 in the first 2 or last 2 positions in the array.
unlucky1({1, 3, 4, 5}) returns true
unlucky1({2, 1, 3, 4, 5}) returns true
unlucky1({1, 1, 1}) returns false
Given an array of ints, return a new array length 2 containing the first and last elements from the original array. The original array will be length 1 or more. The method signature will be public int[] makeEnds(int[] nums)
.
makeEnds({1, 2, 3}) returns {1, 3}
makeEnds({1, 2, 3, 4}) returns {1, 4}
makeEnds({7, 4, 6, 2}) returns {7, 2}
Given an array of ints length 3, write a method public int[] rotateLeft3(int[] nums)
to
return an array with the elements "rotated left" so {1, 2, 3} yields {2, 3, 1}.
rotateLeft3({1, 2, 3}) returns {2, 3, 1}
rotateLeft3({5, 11, 9}) returns {11, 9, 5}
rotateLeft3({7, 0, 0}) returns {0, 0, 7}
Given 2 int arrays, a and b, of any length, write a method
public int[] front11(int[] a, int[] b)
to return a new array with the first element of each array. If either array is length 0, ignore that array.
front11({1, 2, 3}, {7, 9, 8}) returns {1, 7}
front11({1}, {2}) returns {1, 2}
front11({1, 7}, {}) returns {1}