CPSC 124, Spring 2017: Sample Answers to Quiz #4
These are sample answers only. Often, answers that are less
detailed than the ones given here can still receive full credit.
Question 1. Explain what is meant by term subroutine.
Answer. A subroutine consists of the instructions for performing a certain task, that have been chunked together and given a name. Then, to perform that task, the subroutine can be called by name. A subroutine can have parameters that are sent to the subroutine when it is called, and it can have a return value that is returned to the point in the program where the subroutine was called.
Question 2. Write a static subroutine named printArray that prints out all the strings in an array of type String[] (using System.out.println). The array is a parameter to the subroutine, and the subroutine does not return a value.
Answer.
public static void printArray( String[] strings ) { for ( int index = 0; index < strings.length; index++ ) { System.out.println( strings[index] ); } }
Question 3. rite a static subroutine to find the minimum of two numbers of type double. The two numbers are parameters to the subroutine. The minimum value should be the return value of the subroutine. (If the two numbers are equal, it doesn't matter which one is returned.)
Answer.
public static double minimum( double x, double y ) { if ( x < y ) { return x; } else { return y; } } Or, to keep the return statement at the end: public static double minimum( double x, double y ) { double min; if ( x < y ) { min = x; } else { min = y; } return min; }
Question 4. Write a Java statement that will find and print the minimum of the two numbers 2.72 and 3.14, using the subroutine that you wrote for the previous problem.
Answer.
System.out.println( minimum(2.72, 3.14) );