Java

TOPIC 28 – FUNCTIONS, Part 1

 

LESSON WORK

 

 

QUESTION 1 – FUNCTION CALLS

Give a function call for the following prototypes.  Make sure to handle the returned value from the function.


a)

public static double coco(int a)

 

b)
public static int bobo(double t, double g)

 

c)
public static String yabada(String s)

 

QUESTION 2 – PROTOTYPES

 

Give both the class name and the function prototype for the following function calls.

 

a)

double area = Fun.area(12.4, 14.5);

 

b)

String s = Manipulator.initials(firstName, lastName);

 

c)

int x = MyClass.randomNumber();

 

QUESTION 3 – TRIPLING THE VALUE

 

a) Write a function called tripVal that gets an integer as parameter and returns the tripled value of that integer.

 

b) Inside a main function, test your function.

 

QUESTION 4 – AVERAGE CALCULATION FUNCTION


a) Write a function called average that gets 4 double values as parameters and calculates and returns the average of the four.

 

b) Inside a main function, ask the user to provide 4 different averages.  The program then uses the function from a) to calculate the average.

 

QUESTION 5 – MAX OF THREE

a) Write a function called max that gets three integers as arguments.  It returns the maximum of the three integers.

 

b) Inside the same class used in a), write a function called max that gets three doubles as arguments.  It returns the maximum of the three doubles.  Notice that this function has the same name as the previous one but has different argument lists.  This is called function overloading. 

 

c) Again, inside the same class, write a main function that tests both max functions above.

 

QUESTION 6 – SUMMATION

Write a function called summation that gets a positive integer n as argument.  It then calculates and returns the sum of:

 

1 + 2 + 3 + … + n

 

Note: You will have to use a loop.

 

For example, summation(4) returns 10 because 1 + 2 + 3 + 4 is 10.

 

QUESTION 7 – MORE SUMMATION

 

Instead of manually adding up all numbers in a summation from 1 to n, mathematicians figured out a long time ago that we can simply use the following formula instead:

 

 

Write a function called summation2 that gets a positive integer n as argument.  It then calculates and returns the sum of all numbers fro 1 to n by using the formula above.

 

For example, summation(4) return 10 because 4 * 5 / 2 = 10.

 

QUESTION 8 – TEST

 

Inside main, test both your functions summation and summation2 on all values of n from 1 to 20 to make sure they are the same.

 

QUESTION 9 - REFLECTION

 

Which of your two summation functions do you think is easier to code?  Which one do you think is more efficient for the computer to execute?