Problem Class Questions for 1B1a (Programming I)

Week 6 (Starting 17th November)

These questions are all about designing and writing methods, similar to questions that have appeared in past exams and tests.

1. Write a method to reverse the order of the elements in an int array passed as a parameter (int[] reverse(int[] a)). For example, given an array containing [1,2,3,4,5,6], the method would return [6,5,4,3,2,1].

Which array does the method return? Does it reverse the array passed as the parameter or should it create and return a new array? Try both ways.

 

2. Write a method that takes two parameters, an array of integers and a single integer, and returns an array containing all the values in the parameter array that are a multiple of the integer parameter value. The array returned should not have any unused elements (i.e., it should be exactly the right size to hold the multiples or size zero if there are none).

 

3a) Write a method that takes an integer parameter, separates the integer into its individual digits, and returns an array of the integers. For example, with a parameter value of 34567 the array [3,4,5,6,7] would be returned.

b) Do the same for a parameter of type double and return a 2D array, with the first row holding the digits before the decimal point and the second row holding the digits after the decimal point.

 

4. Write a method that takes two parameters, an array of integers and a single integer. The method should display the values in the array centred in a column of the width specified by the single integer parameter.

For example, the method call centreInColumn(array,width) where array is [2345, 3, 45, 123] and width is 8 would display:

|  2345  |
|    3   | 
|   45   |
|   123  | 

Visually the positioning is not perfect but represents the best that can be done given the way that characters are displayed. Determine the rules you will work to. Rather than write a single method it would be easier to write several methods for each step of the process, e.g., convert integer to characters, print one line, print the whole column.

 

5. Write a method that takes a String and a double as parameters. The double number should be converted to a String and formatted according to the contents of the String parameter. The formatted String is then returned.

For example:

format("###.##",123.4567) returns "123.45"

and

format("The answer is: ##.#", 12.34) returns "The answer is: 12.3"

In these examples, the # character represents a digit to be displayed. Make sure that you cover all valid and invalid possibilities. What happens if you try format("#.##",123.45), for example?