INTRO TO OOP FOR FUNCTIONS DATA SCIENCE PROF. JOHN GAUCH OVERVIEW - - PDF document

intro to oop for functions data science
SMART_READER_LITE
LIVE PREVIEW

INTRO TO OOP FOR FUNCTIONS DATA SCIENCE PROF. JOHN GAUCH OVERVIEW - - PDF document

5/18/20 INTRO TO OOP FOR FUNCTIONS DATA SCIENCE PROF. JOHN GAUCH OVERVIEW OVERVIEW OVERVIEW In real life, we often find ourselves doing the same task Functions in Java allow us to reuse code over and over When we declare a function we


slide-1
SLIDE 1

5/18/20 1

INTRO TO OOP FOR DATA SCIENCE

  • PROF. JOHN GAUCH

FUNCTIONS

OVERVIEW

OVERVIEW

§ In real life, we often find ourselves doing the same task

  • ver and over

§ Example: make toast and jam for breakfast in the morning § Example: drive our car from home to work and back § Once we have decided on our favorite way to do these tasks, we can write down the steps we normally take § Make a recipe card for making breakfast items § Write down series of turns to travel from A to B § This written descriptions will let others reuse our work

(c) Prof. John Gauch, Univ. of Arkansas, 2020

3

OVERVIEW

§ Functions in Java allow us to reuse code § When we declare a function we write down the code we want to reuse in our program § We can call a function to execute this code anywhere we want in our program § We can customize a function by providing input parameters and calculate results using this input § Functions provide a fast/simple way to reuse code which saves a lot of programmer time/effort

(c) Prof. John Gauch, Univ. of Arkansas, 2020

4

OVERVIEW

§ Functions play an important role in software development § Break a big problem down into a sequence of smaller problems that we know how to solve § Implement and test solutions to each of the smaller problems using functions § Use the functions we created above to create an effective solution to the big problem § Functions in the same category are often packaged together to create function libraries § Java has created function libraries for input/output, string manipulation, mathematics, random numbers, etc.

(c) Prof. John Gauch, Univ. of Arkansas, 2020

5

OVERVIEW

§ Lesson objectives: § Learn the syntax for declaring functions in Java § Learn how to call and trace the execution of functions § Learn how to define and use function parameters § Study example programs showing their use § Complete online labs on functions § Complete programming project using functions

(c) Prof. John Gauch, Univ. of Arkansas, 2020

6

slide-2
SLIDE 2

5/18/20 2

FUNCTIONS

PART 1 CREATING AND USING FUNCTIONS

DECLARING FUNCTIONS

§ In order to declare a function in Java we need to provide the following information: § The name of the function § List of operations to be performed § Type of data value to be returned § Types and names of parameters (if any) § Declaration of local variables (if any) § Value to be returned to the main program (if any)

(c) Prof. John Gauch, Univ. of Arkansas, 2020

8

DECLARING FUNCTIONS

§ Function return values § The return( ) statement exits the function, and returns a value back to the program where the function was called § You can use the return( ) statement anywhere in function, but the bottom of the function is preferred § The type of the return value depends on the application § Typical mathematical functions return float values § Typical I/O functions return input data or status flags § Some functions perform calculations but return no value (we use the special data type "void" in this case)

(c) Prof. John Gauch, Univ. of Arkansas, 2020

9

DECLARING FUNCTIONS

§ Consider the following programming task: § Prompt the user to input a value between 1..9 § Read the integer value from the user § Loop until a valid input value is entered § Prompt the user to input a value between 1..9 § Read the integer value from the user § We can declare a Java function to package this code together so it can be reused in different programs

(c) Prof. John Gauch, Univ. of Arkansas, 2020

10

DECLARING FUNCTIONS

// Function declaration example static int ReadNum() { int Number = 0; while ((Number < 1) || (Number > 9)) { System.out.print("Enter a number between 1..9: "); Number = scanner.nextInt(); } return( Number ); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

11

Name of the function we are declaring

DECLARING FUNCTIONS

// Function declaration example static int ReadNum() { int Number = 0; while ((Number < 1) || (Number > 9)) { System.out.print("Enter a number between 1..9: "); Number = scanner.nextInt(); } return( Number ); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

12

Operations to be performed by the function

slide-3
SLIDE 3

5/18/20 3

DECLARING FUNCTIONS

// Function declaration example static int ReadNum() { int Number = 0; while ((Number < 1) || (Number > 9)) { System.out.print("Enter a number between 1..9: "); Number = scanner.nextInt(); } return( Number ); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

13

Data type of the function return value

DECLARING FUNCTIONS

// Function declaration example static int ReadNum() { int Number = 0; while ((Number < 1) || (Number > 9)) { System.out.print("Enter a number between 1..9: "); Number = scanner.nextInt(); } return( Number ); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

14

This local variable can only be used within this function

DECLARING FUNCTIONS

// Function declaration example static int ReadNum() { int Number = 0; while ((Number < 1) || (Number > 9)) { System.out.print("Enter a number between 1..9: "); Number = scanner.nextInt(); } return( Number ); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

15

Value returned by the function to the main program

CALLING FUNCTIONS

§ Now that we have declared the function ReadNum how can we use this function in the main program? § We need to specify the following in a function call § The name of the function we wish to execute § Variables passed in as parameters (if any) § Operations to be performed with return value (if any) § The main program will jump to function code, execute it, and return with the value that was calculated § Return values can be used to assign variables or they can be output (we should not ignore them)

(c) Prof. John Gauch, Univ. of Arkansas, 2020

16

CALLING FUNCTIONS

public static void main (String[] args) { … // Function usage example int Num = 0; Num = ReadNum(); cout << "Your Lucky number is " << Num << endl; … }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

17

This function call will cause the main program to jump to the ReadNum function, execute that code and store the return value in variable Num

CALLING FUNCTIONS

§ We can trace the executions functions in a program using the "black box" method § Draw a box for the main program § Draw a second box for the function being called § Draw an arrow from the function call in the main program to the top of the function being called § Draw a second arrow from the bottom of the function back to the main program labeled with the return value § Using this black box diagram we can visualize the execution of the program by following the arrows

(c) Prof. John Gauch, Univ. of Arkansas, 2020

18

slide-4
SLIDE 4

5/18/20 4

CALLING FUNCTIONS

(c) Prof. John Gauch, Univ. of Arkansas, 2020

19

public static int main() { Num = ReadNum(); } static int ReadNum() { return(…); } We leave the main program and jump to the ReadNum function

CALLING FUNCTIONS

(c) Prof. John Gauch, Univ. of Arkansas, 2020

20

public static int main() { Num = ReadNum(); } static int ReadNum() { return(…); } We then execute the code inside the ReadNum function

CALLING FUNCTIONS

(c) Prof. John Gauch, Univ. of Arkansas, 2020

21

public static int main() { … Num = ReadNum(); … } static int ReadNum() { return(…); } When we reach the bottom of the ReadNum function we return a value to the main program. If the user enters the number 6 the return value would be 6 6

CALLING FUNCTIONS

public static int main() { … // Function usage example int Num = 0; Num = ReadNum(); cout << "Your Lucky number is " << Num << endl; … }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

22

ReadNum returned the value 6, which is now stored in Num variable

CALLING FUNCTIONS

public static int main() { … // Function usage example int Num = 0; Num = ReadNum(); cout << "Your lucky number is << Num << endl; Num = ReadNum(); cout << "Your second lucky number is " << Num << endl; … }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

23

Each time we call ReadNum the code in the function will be executed and a new value will be returned

FUNCTIONS WITHOUT RETURN VALUES

§ What happens if a function does not have a return value? § In some cases, we just want a function to print out something like a help message or a command menu § In this case, the function return type is void § Since the function does not need to return anything to the main program, we can omit the return statement § When the code reaches the bottom of the function, it will automatically return to the location the function was called in the main program

(c) Prof. John Gauch, Univ. of Arkansas, 2020

24

slide-5
SLIDE 5

5/18/20 5

FUNCTIONS WITHOUT RETURN VALUES

// Function declaration example static void PrintMenu() { cout << "Welcome to ACME bank:\n"; cout << "Please enter one of the commands below:\n"; cout << " 0 – Quit this banking program\n"; cout << " 1 – Deposit money into your account\n"; cout << " 2 – Withdraw money from your account\n"; cout << " 3 – Transfer money between accounts\n"; }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

25

FUNCTIONS WITHOUT RETURN VALUES

int main() { … // Function usage example PrintMenu(); int Command = scanner.nextInt(); cout << "Command:" << Command << ":\n"; … }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

26

When we call PrintMenu, the program will jump to the function, print the messages, and then return to this location

CODE DEMO

Draw.java

(c) Prof. John Gauch, Univ. of Arkansas, 2020

27

SUMMARY

§ In this section we have shown how a function can be declared in in Java § We have also shown how a function can be called from within the main program § Finally, we have shown how the "box method" can be used to trace the execution of functions in a program

(c) Prof. John Gauch, Univ. of Arkansas, 2020

28

FUNCTIONS

PART 2 PARAMETERS

PARAMETERS

§ A function often needs data to perform desired task § We can pass data into function using parameters § When defining a function, we need to specify the data types and the names of all parameters § When calling the function, we need to provide the values of all parameters in the same order they were defined § Example § To calculate the square of a number in a function, we need to pass in the number to square as a value parameter

(c) Prof. John Gauch, Univ. of Arkansas, 2020

30

slide-6
SLIDE 6

5/18/20 6

PARAMETERS

// Function with value parameter static float Square( float Number ) { float Result = Number * Number; return( Result ); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

31

Number is a float parameter We can use Number in

  • ur function to calculate

desired return value

PARAMETERS

public static int main() … // Calling the Square function cout << Square(3.0) << endl; float Num = 5.0; cout << Square(Num) << endl; … }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

32

Call function with value 3.0 Call function with value 5.0

PARAMETERS

(c) Prof. John Gauch, Univ. of Arkansas, 2020

33

public static int main() { … cout << Square(3.0); … } static float Square(Number=3.0) { … float Result = Number * Number; return(Result); } When we call Square(3.0) we initialize the parameter Number with a value of 3.0

PARAMETERS

(c) Prof. John Gauch, Univ. of Arkansas, 2020

34

public static int main() { … cout << Square(3.0); … } static float Square(Number=3.0) { … float Result = Number * Number; return(Result); } The function calculates and returns a value of 9.0 to the main program 9.0

PARAMETERS

(c) Prof. John Gauch, Univ. of Arkansas, 2020

35

public static int main() { … float Num = 5.0; cout << Square(Num); … } static float Square(Number=5.0) { … float Result = Number * Number; return(Result); } When we call Square(3.0) we initialize the parameter Number with a value of 3.0

PARAMETERS

(c) Prof. John Gauch, Univ. of Arkansas, 2020

36

public static int main() { … float Num = 5.0; cout << Square(Num); … } static float Square(Number=5.0) { … float Result = Number * Number; return(Result); } The function calculates and returns a value of 25.0 to the main program 25.0

slide-7
SLIDE 7

5/18/20 7

SQUARE ROOT EXAMPLE

§ How can we calculate the square root R of a number N? § Use the ancient Babylonian method § Make initial guess of square root value R = N / 2 § Calculate N / R § The correct answer is somewhere between R and N / R § Make new guess R = (R + N / R) / 2 § Keep iterating until the value of R converges (or we get tired of doing this process)

(c) Prof. John Gauch, Univ. of Arkansas, 2020

37

SQUARE ROOT EXAMPLE

§ Example: Calculating square root of 49 § Initial guess R = 49 / 2 = 24.5 § Calculate N/R = 49 / 24.5 = 2 § New guess R = (24.5 + 2) / 2 = 13.25 § Calculate N/R = 49 / 13.25 = 3.69 § New guess R = (13.25 + 3.69) / 2 = 8.47 § Calculate N/R = 49 / 8.47 = 5.78 § New guess R = (8.47 + 5.78) / 2 = 7.125 § Calculate N/R = 49 / 7.125 = 6.877 § New Guess R = (7.125 + 6.877) / 2 = 7.001

(c) Prof. John Gauch, Univ. of Arkansas, 2020

38

SQUARE ROOT EXAMPLE

// Function to calculate square root static double my_sqrt(double number) { double root = number / 2; for (int count = 0; count < 10; count++) root = (root + number / root) / 2; return (root); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

39

With a bottom up approach we implement this function first before completing the main program

SQUARE ROOT EXAMPLE

// Function to calculate square root static double my_sqrt(double number) { double root = number / 2; for (int count = 0; count < 10; count++) root = (root + number / root) / 2; return (root); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

40

Notice that we are looping a fixed number of times

SQUARE ROOT EXAMPLE

// Main body of program public static int main() { double Number = 49; double Root = my_sqrt(Number); System.out.println("Number = " + Number); System.out.println("Root = " + Root); return 0 ; }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

41

With a bottom up approach we use a simple main program to debug the my_sqrt function

SQUARE ROOT EXAMPLE

// Main body of program public static int main() { System.out.print("Enter a positive number: "); double Input = scanner.nextDouble(); if ((Input > 0) System.out.println("Root = " + my_sqrt(Number)); return 0 ; }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

42

In the final version we add a user interface in main and call the my_sqrt function

slide-8
SLIDE 8

5/18/20 8

SUM DIGITS EXAMPLE

§ How can we calculate the sum of the digits in an integer between 0..99999? § Find each of the 5 digits in the number § Add them up to get the sum of digits § How can we implement this using functions? § We can implement a SumDigits function to extract the individual digits of the number and calculate their sum § We can write a main program that prompts the user for input, does error checking, and calls SumDigits to calculate the final answer

(c) Prof. John Gauch, Univ. of Arkansas, 2020

43

SUM DIGITS EXAMPLE

§ Should we implement the function or main program first? § There is no right way or wrong way to do this § If we implement and test the main program before SumDigits, this is called a top down approach § In this case, we need to implement a "dummy" version of SumDigits to test the main program § If we implement and test SumDigits before the main program, this is called a bottom up approach § In this case, we need a "simple" version of the main program to test the SumDigits function

(c) Prof. John Gauch, Univ. of Arkansas, 2020

44

SUM DIGITS EXAMPLE

// Function to calculate sum of digits static int SumDigits(int Number) { // Return answer return (42); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

45

With a top down approach we create a dummy version of this function that has the correct parameters but does not do any real work

SUM DIGITS EXAMPLE

// Main body of program public static int main() { System.out.print("Enter number in [0..99999] range: "); int Input = scanner.nextInt(); if ((Input < 0) || (Input > 99999)) System.out.print("Number must be in [0..99999]"); else System.out.print("Sum digits = " + SumDigits(Input)); return 0 ; }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

46

With a top down approach we write a main program that calls the dummy function

SUM DIGITS EXAMPLE

Top down program output: Enter number in [0..99999] range: 123 Sum digits = 42 Enter number in [0..99999] range: 23456 Sum digits = 42 Enter number in [0..99999] range: 222222 Number must be in [0..99999]

(c) Prof. John Gauch, Univ. of Arkansas, 2020

47

This shows the dummy

  • utput from the function

This shows error checking is working correctly in main program

SUM DIGITS EXAMPLE

§ How can we find the individual digits of the number so we can calculate their sum? § The first digit is easy, just divide by 10000 to trim off the last four digits of the number int Digit1 = Number / 10000; § The last digit is also easy, just use the modulo 10

  • peration to trim off the first four digits of the number

int Digit5 = Number % 10;

(c) Prof. John Gauch, Univ. of Arkansas, 2020

48

slide-9
SLIDE 9

5/18/20 9

SUM DIGITS EXAMPLE

§ The other digits require a careful combination of modulo and division operations to trim off digits from the front and the back of the number int Digit2 = (Number % 10000) / 1000; int Digit3 = (Number % 1000) / 100; int Digit4 = (Number % 100) / 10; § Notice there is a very nice symmetry to these calculations, which is often a sign that you have the correct logic

(c) Prof. John Gauch, Univ. of Arkansas, 2020

49

SUM DIGITS EXAMPLE

// Function to calculate sum of digits static int SumDigits(int Number) { // Get digits and calculate their sum int Digit1 = Number / 10000; int Digit2 = (Number % 10000) / 1000; int Digit3 = (Number % 1000) / 100; int Digit4 = (Number % 100) / 10; int Digit5 = Number % 10; return (Digit1+Digit2+Digit3+Digit4+Digit5); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

50

With a bottom up approach we implement SumDigits function first

SUM DIGITS EXAMPLE

// Main body of program public static int main() { int Input = 12345; int Sum = SumDigits(Input); System.out.println("Input = " + Input); System.out.println("Sum = " + Sum); return 0 ; }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

51

With a bottom up approach we write a very simple main program to call SumDigits and edit this main program to debug the SumDigits code

SUM DIGITS EXAMPLE

Bottom up program output: Input = 12345 Sum = 15

(c) Prof. John Gauch, Univ. of Arkansas, 2020

52

This shows the correct

  • utput from the SumDigits

function but there is no user interface in the main program

SUM DIGITS EXAMPLE

Final program output: Enter number in [0..99999] range: 123 Sum digits = 6 Enter number in [0..99999] range: 23456 Sum digits = 20 Enter number in [0..99999] range: 222222 Number must be in [0..99999]

(c) Prof. John Gauch, Univ. of Arkansas, 2020

53

The final version shows the proper user interface and the correct output from SumDigits

GRADE EXAMPLE

§ Functions are not required to return results at the end of a function, they can also return in the middle of a function § We can demonstrate this with two functions to convert test scores from [0..100] into letter grades [A..F] § Option 1: Use if-else statements to calculate and save letter grade and the return result at the end § Option 2: Use if-else to calculate letter grade and return the result as soon as it is found

(c) Prof. John Gauch, Univ. of Arkansas, 2020

54

slide-10
SLIDE 10

5/18/20 10

GRADE EXAMPLE

// Function to calculate letter grades static char GetGrade( float Average ) { if (Average >= 90) Grade = 'A'; else if (Average >= 80) Grade = 'B'; else if (Average >= 70) Grade = 'C'; else if (Average >= 60) Grade = 'D'; else Grade = 'F'; return Grade; }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

55

Option 1 The function calculates letter grade and returns the result at the end

GRADE EXAMPLE

// Function to calculate letter grades static char GetGrade( float Average ) { if (Average >= 90) return 'A'; if (Average >= 80) return 'B'; if (Average >= 70) return 'C'; if (Average >= 60) return 'D'; return 'F’; }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

56

Option 2 The function calculates letter grade and returns result immediately

GRADE EXAMPLE

public static int main() { … // Calling function to calculate grade float NewScore = 86.4; char NewGrade = GetGrade(NewScore); System.out.println("Your final grade is " + NewGrade); … }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

57

We call the GetGrade function with NewScore as a parameter

GRADE EXAMPLE

(c) Prof. John Gauch, Univ. of Arkansas, 2020

58

public static int main() { … float NewScore = 86.4; char NewGrade = GetGrade(NewScore); … } static char GetGrade( Average=86.4) { … return Grade; } We call GetGrade with Average of 86.4

GRADE EXAMPLE

(c) Prof. John Gauch, Univ. of Arkansas, 2020

59

public static int main() { … float NewScore = 86.4; char NewGrade = GetGrade(NewScore); … } static char GetGrade( Average=86.4) { … Grade = ‘B’; … return Grade; } We calculate value of Grade to be ‘B’

GRADE EXAMPLE

(c) Prof. John Gauch, Univ. of Arkansas, 2020

60

public static int main() { … float NewScore = 86.4; char NewGrade = GetGrade(NewScore); … } static char GetGrade( Average=86.4) { … Grade = ‘B’; … return Grade; } The return value is stored in NewGrade variable in main ‘B’

slide-11
SLIDE 11

5/18/20 11

PRIME FACTORS EXAMPLE

§ How can we calculate and print the prime factors of an integer that is between 1..100? § We need to check to see if the input value can be divided evenly by prime factors less than 100 § We also need to modify the input value by repeatedly dividing it by this prime factor until it is no longer a factor input = 50 2 is a factor, input = 50/2 = 25 5 is a factor, input = 25/5 = 5 5 is a factor, input = 5/5 = 1

(c) Prof. John Gauch, Univ. of Arkansas, 2020

61

PRIME FACTORS EXAMPLE

§ How can we use functions to solve this problem? § We can create a CheckFactors function that takes the input number and the factor we want to test as inputs § We must call this function several times in the main program with different prime factors § Since our input will be [1..100] we only need to check prime factors up to the square root of 100 (i.e. 2,3,5,7)

(c) Prof. John Gauch, Univ. of Arkansas, 2020

62

PRIME FACTORS EXAMPLE

// Function to check one prime factor static int CheckFactor(int number, int factor) { // Loop dividing number by factors while (number % factor == 0) { System.out.println(factor + " is a factor"); number = number / factor; } return number; }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

63

Here we test if factor divides evenly into number

PRIME FACTORS EXAMPLE

// Function to check one prime factor static int CheckFactor(int number, int factor) { // Loop dividing number by factors while (number % factor == 0) { System.out.println(factor + " is a factor"); number = number / factor; } return number; }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

64

Here we divide input number by factor and return the final value

PRIME FACTORS EXAMPLE

// Main body of program public static void main(String[] args) { // Read input value Scanner scnr = new Scanner(System.in); System.out.print("Enter an integer: "); int number = scnr.nextInt(); // Check input value if ((Num < 1) || (Num > 100)) System.out.println("Number must be in [1..100]");

(c) Prof. John Gauch, Univ. of Arkansas, 2020

65

PRIME FACTORS EXAMPLE

… // Calculate prime factors else { Num = CheckFactors(Num, 2); Num = CheckFactors(Num, 3); Num = CheckFactors(Num, 5); Num = CheckFactors(Num, 7); if (Num > 1) System.out.println(Num << " is a factor"); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

66

We call the CheckFactors function four times to check if Num is divisible by 2,3,5,7 and print a message if it is a factor

slide-12
SLIDE 12

5/18/20 12

PRIME FACTORS EXAMPLE

… // Calculate prime factors else { Num = CheckFactors(Num, 2); Num = CheckFactors(Num, 3); Num = CheckFactors(Num, 5); Num = CheckFactors(Num, 7); if (Num > 1) System.out.println(Num << " is a factor"); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

67

The remainder after division is also a prime factor

PRIME FACTORS EXAMPLE

Sample program output: Enter number in [1..100] range: 42 2 is a factor 3 is a factor 7 is a factor Enter number in [1..100] range: 65 5 is a factor 13 is a factor

(c) Prof. John Gauch, Univ. of Arkansas, 2020

68

PRIME FACTORS EXAMPLE

§ How can we extend this program to handle input values greater than 100? § We can add a loop in the main program that calls the CheckFactors function with every value between 2 and the square root of Num to see if they are factors for (int Factor=2; Factor<sqrt(Num); Factor++) CheckFactors(Num, Factor); § This code is shorter but is actually slower because we are also checking non-prime factors (i.e. 4, 6, 8, 9, etc.)

(c) Prof. John Gauch, Univ. of Arkansas, 2020

69

CODE DEMO

Factors.java Prime3.java Prime4.java

(c) Prof. John Gauch, Univ. of Arkansas, 2020

70

SUMMARY

§ In this section we have described how functions with parameters can be used to get data into functions § We have also shown how return values from functions can be used in the main program (or other functions) § Finally, we have discussed several programs that use functions with parameters to solve problems § Square root § Sum of digits § Grade calculation § Prime factors

(c) Prof. John Gauch, Univ. of Arkansas, 2020

71

FUNCTIONS

PART 3 RECURSION

slide-13
SLIDE 13

5/18/20 13

RECURSION

§ Recursion is a very powerful problem solving method § Recursive functions call themselves to solve problems § We reduce "size" of problem each recursive function call § Need to have a terminating condition to stop recursion § Visualize using black box method with inputs and returns § Recursive solutions can also be implemented via iteration § Sometimes the recursive function is smaller § Sometimes the iterative function is faster

(c) Prof. John Gauch, Univ. of Arkansas, 2020

73

RECURSION

§ Example: calculating N factorial § Recursive solution solves problem in terms of itself § Factorial(N) = N * Factorial(N-1) § This is the recurrence relationship § We must stop at some point § Factorial(1) = 1 § This is the terminating condition

(c) Prof. John Gauch, Univ. of Arkansas, 2020

74

FACTORIAL EXAMPLE

// Recursive Factorial function static int Factorial(int Num) { if (Num <= 1) return(1); else return( Num * Factorial(Num-1) ); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

75

This is the terminating condition of for the recursive function Notice that we are recursively calling the Factorial function with a smaller parameter value

FACTORIAL EXAMPLE

(c) Prof. John Gauch, Univ. of Arkansas, 2020

76

main() { … Factorial(3); … } Factorial(3) { … return 3*Factorial(2); … }

  • First, the main program calls Factorial(3)

FACTORIAL EXAMPLE

(c) Prof. John Gauch, Univ. of Arkansas, 2020

77

main() { … Factorial(3); … } Factorial(3) { … return 3*Factorial(2); … } Factorial(2) { … return 2*Factorial(1); … }

  • First, the main program calls Factorial(3)
  • Then, Factorial(3) calls Factorial(2)

FACTORIAL EXAMPLE

(c) Prof. John Gauch, Univ. of Arkansas, 2020

78

main() { … Factorial(3); … } Factorial(3) { … return 3*Factorial(2); … } Factorial(2) { … return 2*Factorial(1); … } Factorial(1) { … return 1; … }

  • First, the main program calls Factorial(3)
  • Then, Factorial(3) calls Factorial(2)
  • Then, Factorial(2) calls Factorial(1)
slide-14
SLIDE 14

5/18/20 14

FACTORIAL EXAMPLE

(c) Prof. John Gauch, Univ. of Arkansas, 2020

79

main() { … Factorial(3); … } Factorial(3) { … return 3*Factorial(2); … } Factorial(2) { … return 2*Factorial(1); … } Factorial(1) { … return 1; … }

1

  • First, the main program calls Factorial(3)
  • Then, Factorial(3) calls Factorial(2)
  • Then, Factorial(2) calls Factorial(1)
  • Then, Factorial(1) returns 1

FACTORIAL EXAMPLE

(c) Prof. John Gauch, Univ. of Arkansas, 2020

80

main() { … Factorial(3); … } Factorial(3) { … return 3*Factorial(2); … } Factorial(2) { … return 2*Factorial(1); … } Factorial(1) { … return 1; … }

2 1

  • First, the main program calls Factorial(3)
  • Then, Factorial(3) calls Factorial(2)
  • Then, Factorial(2) calls Factorial(1)
  • Then, Factorial(1) returns 1
  • Then, Factorial(2) returns 2*1=2

FACTORIAL EXAMPLE

(c) Prof. John Gauch, Univ. of Arkansas, 2020

81

main() { … Factorial(3) … } Factorial(3) { … return 3*Factorial(2); … }

6

Factorial(2) { … return 2*Factorial(1); … } Factorial(1) { … return 1; … }

2 1

  • First, the main program calls Factorial(3)
  • Then, Factorial(3) calls Factorial(2)
  • Then, Factorial(2) calls Factorial(1)
  • Then, Factorial(1) returns 1
  • Then, Factorial(2) returns 2*1=2
  • Then, Factorial(3) returns 3*2=6
  • Finally, the main program prints 6

FACTORIAL EXAMPLE

§ In this case, the iterative solution is the same size and will run slightly faster than the recursive solution // Iterative Factorial function static int Factorial(int Num) { int Product = 1; for (int Count = 1; Count <= Num; Count++) Product = Product * Count; return( Product ); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

82

SUM EXAMPLE

§ Example: calculating sum of all numbers from 1..N § Recursive solution solves problem in terms of itself § Sum(N) = N + Sum(N-1) § This is called the recurrence relationship § We must stop at some point § Sum(1) = 1 § This is called the terminating condition

(c) Prof. John Gauch, Univ. of Arkansas, 2020

83

SUM EXAMPLE

// Recursive summation function static int Sum(int Num) { if (Num <= 1) return(1); else return( Num + Sum(Num-1) ); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

84

This is the terminating condition of for the recursive function Notice that we are recursively calling the Sum function with a smaller parameter value

slide-15
SLIDE 15

5/18/20 15

SUM EXAMPLE

(c) Prof. John Gauch, Univ. of Arkansas, 2020

85

main() { … Sum(3) … } Sum(3) { … Sum(2) … }

6

Sum(2) { … Sum(1) … } Sum(1) { … … }

3 1

  • First, the main program calls Sum(3)
  • Then, Sum(3) calls Sum (2)
  • Then, Sum(2) calls Sum (1)
  • Then, Sum(1) returns 1
  • Then, Sum(2) returns 2+1=3
  • Finally, Sum(3) returns 3+3=6

SUM EXAMPLE

§ In this case the iterative solution is the same size and will run slightly faster than the recursive solution // Iterative summation function static int Sum(int Num) { int Total = 0; for (int Count = 0; Count <= Num; Count++) Total = Total + Count; return(Total); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

86

FIBONACCI EXAMPLE

§ Example: calculating the Nth Fibonacci number from the sequence 1,1,2,3,5,8,13,21,34,55… § Recursive solution solves problem in terms of itself § Fibonacci(N) = Fibonacci(N-1) + Fibonacci(N-2) § This is the recurrence relationship § We must stop at some point § Fibonacci(1) = 1 § Fibonacci(2) = 1 § These are the terminating conditions

(c) Prof. John Gauch, Univ. of Arkansas, 2020

87

FIBONACCI EXAMPLE

§ This recursive function calls itself twice each time it is called so there are a lot of function calls to calculate the answer // Recursive Fibonacci function static int Fibonacci(int Num) { if (Num <= 2) return(1); else return( Fibonacci(Num-1) + Fibonacci(Num-2) ); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

88

FIBONACCI EXAMPLE

// Iterative Fibonacci function int Fibonacci(int Num) { int Num1 = 1; int Num2 = 1; for (int Count = 1; Count < Num; Count++) { int Num3 = Num1 + Num2; Num1 = Num2; Num2 = Num3; } return (Num1); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

89

§ This iterative function is slightly longer than the recursive solution but it is much faster at run time

INFINITE RECURSION

§ What happens if we make a mistake implementing the recurrence relationship? § If the recursive function call has the same parameter value the function will call itself forever § This programming bug is called infinite recursion § Your program will crash with a message like "stack

  • verflow" because it ran out of memory

(c) Prof. John Gauch, Univ. of Arkansas, 2020

90

slide-16
SLIDE 16

5/18/20 16

INFINITE RECURSION

// Infinite recursion function static int Forever(int Num) { if (Num < 0) return(0); else return( Forever(Num) + 1 ); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

91

We are recursively calling the Forever function with the same parameter value

INFINITE RECURSION

§ The corresponding iterative program will not crash, but it will run forever adding one to the Total variable // Infinite iteration function static int Forever(int Num) { int Total = 0; while (Num < 0) Total = Total + 1; return( Total ); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

92

POWER EXAMPLE

§ Example: calculating N raised to integer power P § Recursive solution solves problem in terms of itself § Pow(N, P) = N * Pow(N, P-1) § This is the recurrence relationship § We must stop at some point § Pow(N, 0) = 1 § Pow(N, 1) = N § These are the terminating conditions

(c) Prof. John Gauch, Univ. of Arkansas, 2020

93

POWER EXAMPLE

// Recursive Pow function int Pow(int N, int P) { System.out.print;n("calling pow " + N + " " + P); if (P == 0) return 1; else if (P == 1) return N; else return N * Pow(N,P-1) }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

94

We are calling the Pow function with a smaller parameter value

POWER EXAMPLE

// Main program int main() { System.out.print("Enter number: "); int Number = scanner.nextInt(); System.out.print("Enter power: "); int Power= scanner.nextInt(); System.out.println("Result = " + Pow(Number, Power)); return(0); }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

95

POWER EXAMPLE

Sample program output when number=2, power=8: calling pow 2 8 calling pow 2 7 calling pow 2 6 calling pow 2 5 calling pow 2 4 calling pow 2 3 calling pow 2 2 calling pow 2 1 Result = 256

(c) Prof. John Gauch, Univ. of Arkansas, 2020

96

Notice that the power is decreasing by one with each recursive function call and eventually reaches the terminating condition

slide-17
SLIDE 17

5/18/20 17

POWER EXAMPLE

§ Can we come up with a faster solution? § Divide the exponent in half instead of subtracting one § Recurrence relationships § Pow(N, P) = Pow(N, P/2) * Pow(N, P/2) when P is even § Pow(N, P) = Pow(N, P/2) * Pow(N, P/2) * N when P is odd § Terminating conditions § Pow(N, 0) = 1 § Pow(N, 1) = N

(c) Prof. John Gauch, Univ. of Arkansas, 2020

97

POWER EXAMPLE

int pow2(int N, int P) { System.out.println("calling pow2 " + N + " " + P); if (P == 0) return 1; else if (P == 1) return N;

(c) Prof. John Gauch, Univ. of Arkansas, 2020

98

POWER EXAMPLE

else if (P % 2 == 0) { int temp = pow2(N, P/2); return temp * temp; } else // if (P % 2 == 1) { int temp = pow2(N, P/2); return temp * temp * N; } }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

99

Notice that the power is decreasing by half with each recursive function call to pow2

POWER EXAMPLE

Sample program output when number=2, power=25: calling pow2 2 25 calling pow2 2 12 calling pow2 2 6 calling pow2 2 3 calling pow2 2 1 Result = 33554432

(c) Prof. John Gauch, Univ. of Arkansas, 2020

100

We obtain the same solution after only 5 function calls instead of 25 function calls for the previous implementation

SUMMARY

§ In this section we have focused on recursive functions § We need to implement the recurrence relationship § We need to implement the terminating conditions § Recursion has several pros and cons § Sometimes the recursive solution is smaller and easier to understand than the iterative solution § Recursion can be much slower when there are a large number of "redundant" function calls § Recursion can be much faster when a "divide and conquer" approach is used

(c) Prof. John Gauch, Univ. of Arkansas, 2020

101

FUNCTIONS

PART 4 FUNCTION LIBRARIES

slide-18
SLIDE 18

5/18/20 18

FUNCTION LIBRARIES

§ Function libraries are collections of similar functions grouped together in one file for ease of use § By using built in Java libraries we can increase code reuse and decrease development and debugging time § To use the functions in a Java library we need to add import commands at the top of our program § This tells the Java compiler what functions are available for use in your program § You can read online Java documentation to find out what different functions do and what parameters are needed

(c) Prof. John Gauch, Univ. of Arkansas, 2020

103

FUNCTION LIBRARIES

§ In this section, we will discuss some of the most common and powerful function libraries § java.lang.Math - this library contains all of the common math functions you are used to using § Basic math functions § Exponential and logarithmic functions § Trigonometric functions

(c) Prof. John Gauch, Univ. of Arkansas, 2020

104

MATH LIBRARY

§ Basic Math functions include: § Math.abs(param) – returns the absolute value of of an integer or float param § Math.ceil(param) – rounds a float param value up to the next larger integer § Math.floor(param) – rounds a float param value down to the next smaller integer § Math.round(param) – rounds a float param to the nearest integer (up or down)

(c) Prof. John Gauch, Univ. of Arkansas, 2020

105

MATH LIBRARY

§ Basic Math functions include: § Math.min(param1, param2) – returns the minimum value of the two params § Math.max(param1, param2) – returns the maximum value

  • f the two params

§ Math.random() – returns a pseudo random number in the range [0..1]

(c) Prof. John Gauch, Univ. of Arkansas, 2020

106

MATH LIBRARY

§ Exponential and logarithmic functions include: § Math.E – the most accurate represention of E that can be stored in a double (2.71828…) § Math.exp(param) – returns E raised to the power param § Math.log(param) – returns the natural logarithm of param § Math.log10(param) – returns base10 logarithm of param

(c) Prof. John Gauch, Univ. of Arkansas, 2020

107

MATH LIBRARY

§ Exponential and logarithmic functions include: § Math.pow(param1, param2) – returns param1 raised to the power param2 § Math.sqrt(param) – returns the square root of param, which is the same as Math.pow(param, 0.5) § Math.cbrt(param) – returns the cube root of param, which is the same as Math.pow(param, 1.0/3.0)

(c) Prof. John Gauch, Univ. of Arkansas, 2020

108

slide-19
SLIDE 19

5/18/20 19

MATH LIBRARY

§ Trigonometric functions include: § Math.PI – the most accurate representation of PI that can be stored in a double (3.14159…) § Math.toDegrees(param) – converts an angle in radians into an angle in degrees (same as multiplying by 180/PI) § Math.toRadians(param) – converts an angle in degrees into an angle in radians (same as multiplying by PI/180)

(c) Prof. John Gauch, Univ. of Arkansas, 2020

109

MATH LIBRARY

§ Trigonometric functions include: § Math.sin(param) – returns the sine of angle param (where the angle is in radians) § Math.cos(param) – returns the cosine of angle param (where the angle is in radians) § Math.tan(param) – returns the tangent of angle param (where the angle is in radians)

(c) Prof. John Gauch, Univ. of Arkansas, 2020

110

MATH LIBRARY

§ Trigonometric functions include: § Math.asin(param) – returns the arc sine of a param value between [-1..1], which is the inverse of sin § Math.cos(param) – returns the arc cosine of a param value between [-1..1], which is the inverse of cos § Math.tan(param) – returns the arc tangent of a param value between [-1..1], which is the inverse of tan

(c) Prof. John Gauch, Univ. of Arkansas, 2020

111

MATH LIBRARY

§ See the official Java documentation here

(c) Prof. John Gauch, Univ. of Arkansas, 2020

112

MATH LIBRARY

public static void main(String[] args) { // Calculate and print sin and cos table System.out.printf("%5s %12s %12s\n", "angle", "cos(angle)", "sin(angle)"); for (int Degrees = 0; Degrees <= 360; Degrees += 10) { double Radians = Math.toRadians(Degrees); System.out.printf("%5d %12.5f %12.5f\n", Degrees, Math.cos(Radians), Math.sin(Radians)); } }

(c) Prof. John Gauch, Univ. of Arkansas, 2020

113

CODE DEMO

Random.java

(c) Prof. John Gauch, Univ. of Arkansas, 2020

114

slide-20
SLIDE 20

5/18/20 20

SOFTWARE ENGINEERING TIPS

§ Start your program with "empty" function bodies § Helps debug the main program and parameter passing § Implement and test bodies of functions one at a time § This way you are never far from a running program § Print debugging messages inside each function § To see which function is being called and its parameters § Give functions and parameters meaningful names § Make your code easier to read and understand

(c) Prof. John Gauch, Univ. of Arkansas, 2020

115

SOFTWARE ENGINEERING TIPS

§ Common mistakes when creating functions § Poor choice of the return type of a function § Poor choice of data types for parameters § Common mistakes when calling functions: § Incorrect number of parameters § Incorrect data type of parameters § Incorrect ordering of parameters § Function return value not used properly

(c) Prof. John Gauch, Univ. of Arkansas, 2020

116

SUMMARY

§ In this section we have introduced Java function libraries and some example programs that use these libraries § Learning how to use the the built in Java libraries is an important skill for all programmers to develop § You do not want to waste your time to reinvent a function that has already been written and debugged § We have also discussed several software engineering tips for creating and debugging programs using functions

(c) Prof. John Gauch, Univ. of Arkansas, 2020

117