CS 1073 Introductory Programming
for Scientific Applications
Practice with Functions


Overview: This page gives practice with functions as preparation for Quiz 3. The practice questions will be numbered in red.

In each case you should actually try out your solution in NetBeans before looking at my answer. (You get almost no benefit from just looking at the answer.)


First Starting Point: The function min: :


// Min: test a min function
public class Min {

   public static int min(int x, int y) {
      if (x < y) return x;
      else return y;
   }

   public static void main(String[] args) {
      System.out.println(min(13, 47));
   }
}
Output: 13

Practice Exercises:

  1. Add a function max very similar to min. Test it in the main function using System.out.println(max(13, 47));

  2. Write a function min with three int parameters. You can use the same name min because the system will keep the one with three parameters separate from the one with two parameters. Here's how you should write this version of min: Suppose the parameters are named x, y, and z. (Remember, these are formal parameters and we can give them any name we want.) First use the old min to take the minimum of x and y. Save the result in a new variable w. Now use the old minimum to find the minimum of w and z, and return this. Test this new min function with:

      
      System.out.println(min(13, 47, 96));
      System.out.println(min(96, 13, 47));
      System.out.println(min(47, 96, 13));