sound check some final words on methods recall: three major paradigms for programming

103
Sound Check

Upload: doris-stanley

Post on 29-Dec-2015

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Sound Check

Page 2: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Some Final Words on Methods

Page 3: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Programming Paradigms

Procedural Programming

‘Imperative’ assignment used to create state, andprocedures manipulate state. E.g., C, Assembly, Pascal int y; int x = 3; y = manipulateData(x);

Functional Programming

Functions (procedures that do not depend on outsidedata) are used to provided data. E.g., Lisp.

(defun check-member (input-item input-list) (cond ((null input-list) nil) ((equal input-item (first input-list)) T) (T (check-member input-item (rest input-list)))))

Programming Paradigms

Procedural Programming

‘Imperative’ assignment used to create state, andprocedures manipulate state. E.g., C, Assembly, Pascal int y; int x = 3; y = manipulateData(x);

Functional Programming

Functions (procedures that do not depend on outsidedata) are used to provided data. E.g., Lisp.

(defun check-member (input-item input-list) (cond ((null input-list) nil) ((equal input-item (first input-list)) T) (T (check-member input-item (rest input-list)))))

RECALL:Three major

paradigms forprogramming

Object-Oriented Programming

All data exists in objects; interaction occurs only betweenobjects. Even numbers are objects that know how to addthemselves. E.g., SmallTalk:

| array |array := Array new: 5.rect := 0@0 corner: [email protected] to: array size do: [ :item | rect origin: item@item. array at: item put: rect copy ].

Java:

Object-oriented, but not 100% OO, since it containsprimitives, and tolerates some (hopefully small) degree ofprocedural programming.

Programming ParadigmsObject-Oriented Programming

All data exists in objects; interaction occurs only betweenobjects. Even numbers are objects that know how to addthemselves. E.g., SmallTalk:

| array |array := Array new: 5.rect := 0@0 corner: [email protected] to: array size do: [ :item | rect origin: item@item. array at: item put: rect copy ].

Java:

Object-oriented, but not 100% OO, since it containsprimitives, and tolerates some (hopefully small) degree ofprocedural programming.

Programming Paradigms

Page 4: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Java MethodsJava MethodsThere exists in Java a single construct, the method, for both procedures and functions:

• when a procedure is called for, specify the return type “void” before method name

public void printHelloWorld( ) {

System.out.println(“Hello World!”);

} // of printHelloWorld

• Note: All methods must have parentheses for parameters . . . even if no parameters!

QuickReview

Page 5: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Single construct for both procedures and functions:

• when a function is called for, specify the appropriate return type before method name

public float average (float fNum1, float fNum2, float fNum3) { float fReturnVal; fReturnVal = (fNum1 + fNum2 + fNum3)/ 3; return (fReturnVal); } // of average

Java MethodsJava Methods

QuickReview

Page 6: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Method Signatures“The signature of a method consists of the name of the method and the number and types of formal parameters to the method. A class may not declare two methods with the same signature, or a compile time error occurs.”

--Java Language Specification s.8.4.2

Method overloading occurs when identically named methods have different signatures.

public int getCube(int iNum){return iNum*iNum*iNum;

}

public int getCube(float fNum){return (int)(fNum*fNum*fNum);

}

public int getCube(double dNum){return (int) (dNum*dNum*dNum);

}

QuickReview

Page 7: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

ParametersParametersParametersParameters

• Unlike Pseudocode, Java only has “in” Unlike Pseudocode, Java only has “in” parameters.parameters.

• Thus no need to declare Thus no need to declare inin, , in/outin/out or or outout ‘cause they’re all ‘cause they’re all ININ

• Parameters do need to be declared just Parameters do need to be declared just like variables:like variables:

public void demo(public void demo(int iint i, , float float xx))

• More about parameters when we discuss More about parameters when we discuss objectsobjects

• Unlike Pseudocode, Java only has “in” Unlike Pseudocode, Java only has “in” parameters.parameters.

• Thus no need to declare Thus no need to declare inin, , in/outin/out or or outout ‘cause they’re all ‘cause they’re all ININ

• Parameters do need to be declared just Parameters do need to be declared just like variables:like variables:

public void demo(public void demo(int iint i, , float float xx))

• More about parameters when we discuss More about parameters when we discuss objectsobjects

Page 8: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Where do Methods Go?

Methods (and variables) are contained in Classes, as either class or instance members. More on creating classes and objects shortly . . .

class zippy {int pin;public String yow() {

// some code }}

QuickReview

Page 9: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Questions?

Page 10: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Iteration

Page 11: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Java Basics: Iteration ConstructsJava Basics: Iteration Constructs

• In Pseudocode, we had a single iteration construct, flexible enough to be used in all iteration contexts.

Actually (if you were paying attention last semester) we talked about three kinds of loops:

Sentinal Loops

Test-Last Loop

N-and-a-half Loops

Actually (if you were paying attention last semester) we talked about three kinds of loops:

Sentinal Loops

Test-Last Loop

N-and-a-half Loops

Page 12: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Java Basics: Iteration ConstructsJava Basics: Iteration Constructs

• In Pseudocode, we had a single iteration construct, flexible enough to be used in all iteration contexts.

• Java, like most programming languages, does not provide a single flexible construct.

• Instead, Java offers three special case loop constructs, each good for a particular context.

• Do not get accustomed to only one of them and try to use it for all situations.

• To use them wisely, you should consider not only how they work, but also when each is best used…

Page 13: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

When repeating steps, people naturally want to follow the pattern:

get a value, then process that value

The while loop construct calls for the unnatural pattern:

obtain the first loop control value before entering the loop itself;

then, within the loop body,

first do the process steps,

then do the get next steps

Java Iteration Constructs: “While Loops”Java Iteration Constructs: “While Loops”

Page 14: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Unnatural?

while(You haven’t gotten to my street)

{

Keep going straight

}

turn right

Page 15: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Java example:

<get first value>while (condition){ <process value> <get next value>}

Pseudocode:

<get first value>loop exitif NOT(condition) <process value> <get next value>endloop

Java Iteration Constructs: “While Loops”Java Iteration Constructs: “While Loops”

Pseudocode flavor: Sentinal

Page 16: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Java example:

do { statement 1; ... statement N; } while (condition);

Java Iteration Constructs: “Do While Loops”Java Iteration Constructs: “Do While Loops”

Pseudocode:

loop statement 1 ... statement N exitif (NOT(condition)) endloop

Pseudocode flavor: Test Last

Page 17: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Pseudocode:

i isoftype Num i <- 0 loop exitif (i =>10) <some statements> i <- i + 1 endloop

Java Iteration Constructs: “For Loops”Java Iteration Constructs: “For Loops”

Java example:

int i; for (i=0; i<10; i++) { <some statements> }

Java syntax: for (<initialization>; <continue if>;<increment>)

Page 18: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Secret! A for Loop can be exactly written as a

while loop

i = 0;

while (i < 10)

{

System.out.println(i);

i++;i++;

}

for(i = 0; i < 10; i++i++)

{

System.out.println(i);

}

This will help you understand the sequence of operations of a for loop

Page 19: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Common Problems with For Loops include:

Java Iteration Constructs: “For Loops”

for (i=0; i<N; i++);{ … }

for (int i=0; i<N; i++){…}

--variable declared inside for loop signature; caution:

--the variable may be needed outside the for loop structure

--Spins on ending semicolon; code in braces executed once!

Page 20: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Potential Confusion

public class Forex

{

static int i = 42;

public static void main(String args[])

{

for(int i=0; i < 5; i++)

{

System.out.println(i);

}

System.out.println(i);

}

}

Page 21: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Output

0

1

2

3

4

42

Page 22: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

--The term “control variable” refers to the variable whose value is tested to determine if the loop should continue for another iteration or halt.

--For example, variable thisVar, below:

while (thisVar < = SOME_CONSTANT)

--To determine which loop construct is appropriate for a given situation, ask yourself “where does the control variable’s value come from?”

Java Iteration Constructs: When to UseJava Iteration Constructs: When to Use

ASK:ASK:

Is it simply a count of the number of iterations?

Is it a value that the loop itself must compute?

Is it a value that already exists somewhere, and the loop only obtains it from elsewhere?

Page 23: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

The for loop: used when the control variable is a simple count of the number of iterations,

e.g.: “create a loop that reads and processes the next 100 numbers.”

The while loop: used when the control variable has a value that already exists and is simply obtained by the loop.

e.g.: “create a loop that reads in numbers and processes them until it reads in a 100.”

The do-while loop: used when the control variable’s value must be calculated by the loop itself.

e.g.: “create a loop that reads in numbers until their sum is greater than 100.”

Java Iteration Constructs: When to UseJava Iteration Constructs: When to Use

Page 24: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Which loop construct would you use if...

Java Iteration Constructs: ReviewJava Iteration Constructs: Review

You need to perform a series of steps exactly N times?

You need to traverse a linked list of unknown size, and stop when you find a certain value?

You need to perform a series of steps at least once, and continue performing these steps for an an unknown number of times

Page 25: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Iteration Reiteration

–Three kinds of iteration – for (...;...;...) {...} loops

– Fixed number of iterations

– while (...) {...} loops– Iteration condition evaluated in advance

– do {...} while (...) loops– Iteration condition evaluated in the loop

Page 26: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Questions?

Page 27: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Arrays of Primitives• The Idea:

Same concepts you know from Pseudocode

A few differences in implementation

• Java array declaration:

<elemType>[ ] <arrID> = new <elemType>[<size>];

e.g.: to declare an array of ten ints for storing numerical grades...

int[ ] iGradeArray = new int[10];

• Array declaration error:

using parentheses, not brackets, e.g.,

int[ ] iGradeArray = new int(10);

Page 28: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Details

• The odd looking syntax is because arrays (even arrays of primitives) are objects.

• We'll explain in detail once we get to objects...

int[ ] iGradeArray = new int[10];

int iGradeArray[ ] = new int[10];

Page 29: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Example:• declare iGradeArray of 10 ints• initialize all 10 values to 0

int[ ] iGradeArray = new int[10];int i; // when declaring and manipulating arrays, // you may use the single-letter IDers // i, j, k for indices due to convention // (everybody knows what it is)

for (i=0; i < iGradeArray.length; i++) { iGradeArray[i] = 0;} // for loop

Notes:•Arrays know their own length• length is a field, not a method• Arrays are statically sized: you cannot change the length after declaration.• All arrays are objects, thus you must declare a reference, and instantiate it, and initialize it

ArraysArrays

Great idea!if you changethe array size,you need onlychange theinstantiation.

Page 30: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

More Notes:• Array indices begin at 0, not at 1• So, length is one greater than iMAX_INDEX• Thus, an error if you do:

int[ ] iGradeArray = new int[10];int i; for (i=1; i <= iGradeArray.length; i++){ iGradeArray[i] = 0;} // for loop

• Code above attempts to access elements 1..10• But... you have indices 0..9• So: it misses the 1st element (which is at index 0) it tries to go past 10th element (which is at index 9)

ArraysArrays

Page 31: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Questions?

Page 32: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Sample Quiz ProblemSample Quiz ProblemGiven an array of ints, return the index of the largest element. Use the code below.

public int getLargestIndex(int[ ] iArray){

/* YOUR CODE GOES HERE */

}

Page 33: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Sample Quiz ProblemSample Quiz ProblemGiven an array of ints, return the index of the largest element. Use the code below.

public int getLargestIndex(int[ ] iArray) { int iLargest = -9999;

int iCounter;for (iCounter = 0; iCounter < iArray.length;

iCounter++) { if (iLargest < iArray[iCounter]) iLargest = iArray[iCounter]; } return iLargest;}// getLargestIndex

Does this work?

Page 34: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Sample Quiz ProblemSample Quiz ProblemGiven an array of ints, return the index of the largest element. Use the code below.

public int getLargestIndex(int[ ] iArray) { int iLargest = -9999;

int iCounter;for (iCounter = 0; iCounter < iArray.length;

iCounter++) { if (iLargest < iArray[iCounter]) iLargest = iArray[iCounter]; } return iLargest;}// getLargestIndex

What if all the values are less than -9999

Page 35: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Sample Quiz ProblemSample Quiz ProblemGiven an array of ints, return the index of the largest element. Use the code below.

public int getLargestIndex(int[ ] iArray) { int iLargest = iArray[0];

int iCounter;for (iCounter = 0; iCounter < iArray.length;

iCounter++) { if (iLargest < iArray[iCounter]) iLargest = iArray[iCounter]; } return iLargest;}// getLargestIndex How about this?

Page 36: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Sample Quiz ProblemSample Quiz ProblemGiven an array of ints, return the index of the largest element. Use the code below.

public int getLargestIndex(int[ ] iArray) { int iLargest = iArray[0];

int iCounter;for (iCounter = 1; iCounter < iArray.length;

iCounter++) { if (iLargest < iArray[iCounter]) iLargest = iArray[iCounter]; } return iLargest;}// getLargestIndex

Why not start outiCounter at 1, and not0 like most for loops?

Page 37: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Sample Quiz ProblemSample Quiz ProblemGiven an array of ints, return the index of the largest element. Use the code below.

public int getLargestIndex(int[ ] iArray) { int iLargest = iArray[0];

int iCounter;for (iCounter = 1; iCounter < iArray.length;

iCounter++) { if (iLargest < iArray[iCounter]) iLargest = iArray[iCounter]; } return iLargest;}// getLargestIndex Now it should be perfect!

Page 38: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Sample Quiz ProblemSample Quiz ProblemGiven an array of ints, return the index of the largest element. Use the code below.

public int getLargestIndex(int[ ] iArray) { int iLargest = iArray[0];

int iCounter;for (iCounter = 1; iCounter < iArray.length;

iCounter++) { if (iLargest < iArray[iCounter]) iLargest = iArray[iCounter]; } return iLargest;}// getLargestIndex

Test taking is aboutREADING THE DIRECTIONS

NOTE THIS!

NOTE THIS!

Page 39: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Sample Quiz ProblemSample Quiz ProblemWhat’s the solution? This is a good problem to workout on your own. We don’t want the largest VALUE, we instead want the INDEX of the largest value.

Page 40: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Lessons LearnedLessons Learned

Read the question carefully.

Don’t fall into habits (e.g., all for loops must start with the counter at 0).

Don’t make assumptions about input data (e.g., -99999 is NOT a good initial value).

Trace your code; watch for simple >, < errors.

Page 41: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Questions?

Page 42: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Recursion

Classes and Objects

Constructors

Object References

Parameters

The Road Ahead

Today

Page 43: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

A QuestionHow many people here don’t like recursion?

Why not?

A Promise: By the end of this lecture, you will say:

“Recursion Rocks My World!”

Page 44: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

RecursionRecursion

Let’s say you place two rabbits in a hutch.

What’s going to happen?

Page 45: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

If it takes two months for rabbits to reach maturity, in two months you’ll have one productive pair and one (brand new) non-productive pair. (This assumes all rabbits live up to their reputation.)

Two Months Later...

original rabbits new rabbits

Page 46: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

1 month old 0 months old

The next month, you get another pair . . .

The rabbits keep at it.

Page 47: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

SupposeWhat if:

The rabbits always had two offspring, always male and female;

Rabbits always reached maturity in two months;

No rabbit dies.

How many pairs of rabbits do you have in a year?

1111

2222

3333

Page 48: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Hare Raising Story

Start

End Month 5

End Month 1

End Month 2

End Month 3

End Month 4

= one m/f pair

KEY

Page 49: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

PairsPairs of Rabbits of Rabbits

1

2

3

4

5

6

7

8

9

10

11

12

Month Productive Non-Productive Total

0

1

1

2

3

5

8

13

21

34

55

89

0

1

1

2

3

5

8

13

21

34

55

1 1

1

2

3

5

8

13

21

34

55

89

144

See apattern

yet?

Page 50: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Let’s Take Another ExampleInstead of rabbits, let’s use geometry.

Draw a square of size 1.Rotating 90 degrees, add to it a square of size 1.Rotating 90 degrees again, add a square of size 2.Again, rotate and add a square of size 3, and so on.

Keep this up for the sequence we noted in the table:

1, 1, 2, 3, 5, 8, 13, 21, . . . ,

What do you see?

Page 51: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

1

Page 52: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

1

Page 53: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

2

Page 54: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

3

Page 55: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

5

Page 56: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

8

Page 57: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

13

Page 58: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

21

Page 59: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

11

2

3

58

13

21

Page 60: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Does this look familiar?

Page 61: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

It’s not just about rabbits.

Page 62: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

The TruthThe Truthis Out Thereis Out There

Page 63: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

See the pattern?

1

2

3

4

5

6

7

8

9

10

11

12

Month Productive Non-Productive Total

0

1

1

2

3

5

8

13

21

34

55

89

0

1

1

2

3

5

8

13

21

34

55

1 1

1

2

3

5

8

13

21

34

55

89

144

We used brute force to find the progression:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... ,

It turns out this pattern is repeated in many places: sea shells, sun flowers, pine cones, the stock market, bee hives, etc.

It’s the FibonacciSequence.

Page 64: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Writing the FormulaGiven:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... ,

Can we write this as a formula for any number, n?

This guy could:This guy could:

Jacques Binet(1786-1856)

1+ 1-5 5

2 2-

n n

Fib(n) =

But let’s be honest. We’re not as smart as him.

But that’s OK. We can code.

Page 65: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

What If You Can’t Find the Formula?

Suppose you didn’t know:

1+ 1-5 5

2 2-

n n

Fib(n) =

You could take Math 3012 or you could instead manage with:

Fib(n) = Fib(n-1) + Fib(n-2),Fib(0) = 0;Fib(1) = 1;

(The value at any given place is the sum of the two prior values.)

Which onewould yourrather codeand debug?

For someproblems,there mightnot exist aformula, andrecursion isyour onlyoption.

Page 66: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Recursive Fibonacci

Fib(n) = Fib(n-1) + Fib(n-2),Fib(0) = 0;Fib(1) = 1;

We have our general rule:

We can say a few things about it:

It’s defined recursively (duh).

It has a terminal condition (AHA!)

It can be determined and calculated (addition).

1

2

3

Page 67: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Coding Fibonaccipublic class FibTest {

public static int fib (int num) {

}// FibTest

What do we know to start with? We know that

we need a method thatreturn the Fibonacci

value for a number at agiven position.

This suggests a methodthat gives and gets an int

Page 68: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Coding Fibonaccipublic class FibTest {

public static int fib (int num) {if (num == 0) return 0;

}// FibTest

What’s the FIRST thing we dowith a recursive method?

We plan on how it will terminate!

We know one special casefor the Fibonacci sequence:

F(0) = 0

Page 69: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Coding Fibonaccipublic class FibTest {

public static int fib (int num) {if (num == 0) return 0;else if (num == 1) return 1;

}// FibTest

We also know asecond special casethat could terminate

our recursion:

F(1) = 1.

Page 70: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Coding Fibonaccipublic class FibTest {

public static int fib (int num) {if (num == 0) return 0;else if (num == 1) return 1;else return fib(num-1) + fib(num-2);

}

}// FibTest

The last part of ourformula is merely:

F(n) = F(n-1) + F(n-2)

Page 71: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Coding Fibonaccipublic class FibTest {

public static int fib (int num) {if (num == 0) return 0;else if (num == 1) return 1;else return fib(num-1) + fib(num-2);

}

}// FibTest

Is this safe? What if someonepassed in 0 to our method?

What happens?

What if they passed in 1?

Page 72: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Coding Fibonaccipublic class FibTest {

public static int fib (int num) {if (num == 0) return 0;else if (num == 1) return 1;else return fib(num-1) + fib(num-2);

}

public static void main(String[] args) {for (int i=0; i < 10; i++) System.out.println (fib(i));

}

}// FibTestIt is our responsibilityto write a main to test

this method.

Page 73: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Coding Fibonaccipublic class FibTest {

public static int fib (int num) {if (num == 0) return 0;else if (num == 1) return 1;else return fib(num-1) + fib(num-2);

}

public static void main(String[] args) {for (int i=0; i < 10; i++) System.out.println (fib(i));

}

}// FibTestAre we done?

What about negativenumbers? More work is needed

Page 74: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Recursion ReviewSo far, we’ve seen that for recursive behavior:

1) Recursion exists in all of nature.

2) It’s easiereasier than memorizing a formula. Not every problem has a formula, but every problem can be expressed as a series of small, repeated steps.

3) Each step in a recursive process should be small, calculable, etc.

4) You absolutely need a terminating condition.

Page 75: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Honesty in Computer Science1. To make life easy the typical examples given for

recursion are factorial and the Fibonacci numbers.

2. Truth is the Fibonacci is a horror when calculated using “normal” recursion and there’s not really any big advantage for factorial.

3. So why all the fuss about recursion?

4. Recursion is absolutely great when used to write algorithms for recursively defined data structures like binary trees. Much easier than iteration!

5. Recursion is excellent for any divide & conquer algorithm like...

Page 76: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

One More ExampleSuppose we wanted to create a method that solve:

Pow(x, y) = xy

In other words, the method returned the value of one number raised to the power of another:

public static double pow (double value, int exponent);

Page 77: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Planning the MethodUnlike the Fibonacci example, our mathematical formula is not the complete answer.

Pow(x, y) = xy

We’re missing some termination conditions.

But we know:

x1 = x;

x0 = 1;

So we could use these as our terminating condition.

Page 78: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Attempt #1public static double pow(double value, int exponent){ if (exponent == 0) return 1D;

Always, always start withsome sort of terminating

condition. We know any numberraised to the zero power is one.

Page 79: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Attempt #1public static double pow(double value, int exponent){ if (exponent == 0) return 1D; else if (exponent == 1) return value;

... and any number raised to thepower of one is itself.

Page 80: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Attempt #1public static double pow(double value, int exponent){ if (exponent == 0) return 1D; else if (exponent == 1) return value; else return value * pow (value, exponent--);}

For all other values, we canreturn the number times the

recursive call, using our exponentas a counter. Thus, we calculate:

26 = 2*2*2*2*2*2

Page 81: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Attempt #1public static double pow(double value, int exponent){ if (exponent == 0) return 1D; else if (exponent == 1) return value; else return value * pow (value, exponent--);}

When we run this, however, badthings happen. The program

crashes, having caused a stack overflow. How can we solve this?

Page 82: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Attempt #1public static double pow(double value, int exponent){ if (bDEBUG) System.out.println (“Entering with: “ + value + “, and exp: “ + exponent); if (exponent == 0) return 1D; else if (exponent == 1) return value; else { return value * pow (value, exponent--); }}

Page 83: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Attempt #1public static double pow(double value, int exponent){ if (bDEBUG) System.out.println (“Entering with: “ + value + “, and exp: “ + exponent); if (exponent == 0) return 1D; else if (exponent == 1) return value; else { return value * pow (value, exponent--); }}

Our debug statement tells us that the exponent is never being decreased.Evidently, the “exponent--” line is

not being evaluated before the recursivecall takes place. As it turns out, the

post-decrement operator -- is the problem.

DOH!

DOH!

Page 84: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Attempt #1public static double pow(double value, int exponent){ if (exponent == 0) return 1D; else if (exponent == 1) return value; else { exponent = exponent - 1; return value * pow (value, exponent); }}

We decide that typing one extraline takes less time than debugging

such a subtle error. Things areworking now.

Page 85: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

“Do I Have to Use Recursion?”public static double pow(double value, int exponent){ if (exponent == 0) return 1D; else if (exponent == 1) return value; else { exponent = exponent - 1; return value * pow (value, exponent); }}

How many would have preferred to do this with a “for loop” structure or some other iterative solution?

How many think we can make our recursive method even faster than iteration?

Page 86: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Nota BeneOur power function works through brute force recursion.

28 = 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2

But we can rewrite this brute force solution into two equal halves:

28 = 24 * 24

and24 = 22 * 22

and22 = 21 * 21

andanything to the power 1 is itself!

Page 87: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

And here's the cool part...

28 = 24 * 24

Since these are the same we don't have to calculate them both!

Page 88: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

AHA!

So the trick is knowing that 28 can be solved by dividing the problem in half and using the result twice!

So only THREE multiplication operations have to take place:

28 = 24 * 24

24 = 22 * 22

22 = 21 * 21

Page 89: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

"But wait," I hear you say!

You picked an even power of 2. What about our friends the odd numbers?

Okay we can do odds like this:

2odd = 2 * 2 (odd-1)

Page 90: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

"But wait," I hear you say!

You picked a power of 2. That's a no brainer!

Okay how about 221

221 = 2 * 220 (The odd number trick)

220 = 210 * 210

210 = 25 * 25

25 = 2 * 24

24 = 22 * 22

22 = 21 * 21

Page 91: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

"But wait," I hear you say!

You picked a power of 2. That's a no brainer!

Okay how about 221

221 = 2 * 220 (The odd number trick)

220 = 210 * 210

210 = 25 * 25

25 = 2 * 24

24 = 22 * 22

22 = 21 * 21

That's 6 multiplications instead of 20 and it getsmore dramatic as the exponent increases

Page 92: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

The Recursive InsightIf the exponent is even, we can divide and conquer so it can be solved in halves.

If the exponent is odd, we can subtract one, remembering to multiply the end result one last time.

We begin to develop a formula:

Pow(x, e) = 1, where e == 0 Pow(x, e) = x, where e == 1 Pow(x, e) = Pow(x, e/2) * Pow(x,e/2), where e is even Pow(x, e) = x * Pow(x, e-1), where e > 1, and is odd

Page 93: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Solution #2public static double pow (double value, int exponent){ if (exponent == 0) return 1D; else if (exponent == 1) return value;

}

We have the same basetermination conditions

as before, right?

Page 94: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Solution #2public static double pow (double value, int exponent){ if (exponent == 0) return 1D; else if (exponent == 1) return value; else if (exponent % 2 == 0) {

}

This little gem determines if a number is odd or even.

Page 95: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Solution #2public static double pow (double value, int exponent){ if (exponent == 0) return 1D; else if (exponent == 1) return value; else if (exponent % 2 == 0) { exponent = exponent / 2;

}

We next divide the exponent in half.

Page 96: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Solution #2public static double pow (double value, int exponent){ if (exponent == 0) return 1D; else if (exponent == 1) return value; else if (exponent % 2 == 0) { exponent = exponent / 2; double half = pow (value, exponent);

}

We recurse to find that half of the brute force

multiplication.

Page 97: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Solution #2public static double pow (double value, int exponent){ if (exponent == 0) return 1D; else if (exponent == 1) return value; else if (exponent % 2 == 0) { exponent = exponent / 2; double half = pow (value, exponent); return half * half;

}

And return the twohalves of the equation

multiplied by themselves

Page 98: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Solution #2public static double pow (double value, int exponent){ if (exponent == 0) return 1D; else if (exponent == 1) return value; else if (exponent % 2 == 0) { exponent = exponent / 2; double half = pow (value, exponent); return half * half; } else { exponent = exponent - 1;

}

If the exponent is odd,we have to reduce it

by one . . .

Page 99: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Solution #2public static double pow (double value, int exponent){ if (exponent == 0) return 1D; else if (exponent == 1) return value; else if (exponent % 2 == 0) { exponent = exponent / 2; int half = pow (value, exponent); return half * half; } else { exponent = exponent - 1; double oneless = pow (value, exponent);

}

And now the exponent iseven, so we can just

recurse to solve that portionof the equation.

Page 100: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Solution #2public static double pow (double value, int exponent){ if (exponent == 0) return 1D; else if (exponent == 1) return value; else if (exponent % 2 == 0) { exponent = exponent / 2; int half = pow (value, exponent); return half * half; } else { exponent = exponent - 1; double oneless = pow (value, exponent); return oneless * value; }} We remember to multiply the value

returned by the original value, since we reduced the exponent by one.

Page 101: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Recursion vs. Iteration:Those of you who voted for an iterative solution are likely going to produce:

O(N)

In a Dickensian world, you would be fired for this.

While those of you who stuck it out with recursion are now looking at:

O(log2n)

For that, you deserve a raise.

Page 102: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming

Questions?

Page 103: Sound Check Some Final Words on Methods RECALL: Three major paradigms for programming