CSCI 2212: Intermediate Programming / C...

40
... 1/40 CSCI 2212: Intermediate Programming / C Recursion Alice E. Fischer November 13 and 16, 2015

Transcript of CSCI 2212: Intermediate Programming / C...

Page 1: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 1/40

CSCI 2212: Intermediate Programming / CRecursion

Alice E. Fischer

November 13 and 16, 2015

Page 2: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 2/40

Outline

What is Recursion?

Recursively Defined Images

What is a Recursive Function?

How Does A Recursive Function Work?

Recursive Coding Patterns

Page 3: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 3/40

What is Recursion?

I. What is Recursion?

Page 4: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 4/40

What is Recursion?

Page 5: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 5/40

What is Recursion?

Recursive Definition

A thing defined in terms of itself.

Definition: Recursion – see “Recursion”.

Google Recursion, you get – Did you mean: “Recursion” ?.

Definition: Recursion – If you still don’t get it, see “Recursion”.

Definition: Fractal – A rough or fragmented geometric shape thatcan be split into parts, each of which is (at least approximately) areduced-size copy of the whole.

Page 6: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 6/40

What is Recursion?

Page 7: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 7/40

What is Recursion?

The Mandlebrot Set

z0 = 0zn+1 = z2

n + cwhere c is a complex number (a point on the complex plain)

A complex number, c, is part of the Mandelbrot set if theabsolute value of zn never exceeds a limit (which depends on c)however large n gets.

In visualizations, points on the plane that belong to the MandlebrotSet are colored black. The other colors encode the number ofrepetitions required, for that point, until the computation diverges.

Page 8: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 8/40

What is Recursion?

The Mandlebrot Set

Page 9: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 9/40

What is Recursion?

Self-similar at a smaller scale

Page 10: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 10/40

What is Recursion?

Zooming In

Page 11: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 11/40

What is Recursion?

Page 12: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 12/40

Recursively Defined Images

The Sierpinski Triangle

Page 13: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 13/40

Recursively Defined Images

Fractal Tree

Page 14: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 14/40

Recursively Defined Images

Hilbert’s Space-Filling Curve: Recursive Definition

Each cup is replaced by four cups of half the size, connected by three links.

Page 15: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 15/40

Recursively Defined Images

Hilbert’s Space-Filling Curve – Order 1

Page 16: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 16/40

Recursively Defined Images

Hilbert’s Space-Filling Curve – Building Order 2

Page 17: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 17/40

Recursively Defined Images

Hilbert’s Space-Filling Curve – Building Order 2

Page 18: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 18/40

Recursively Defined Images

Hilbert’s Space-Filling Curve – Orders 1 and 2

Page 19: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 19/40

Recursively Defined Images

Hilbert’s Space-Filling Curve – Orders 1, 2, and 3

Page 20: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 20/40

What is a Recursive Function?

I. What is a Recursive Function in C?

A method of repetition.A top-down way to solve a problem.

A function that calls itself.

Page 21: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 21/40

What is a Recursive Function?

A Method of Repetition

Recursion is a control structure for implementing repetition.It is nearly as old as programming languages.

I FORTRAN (1957) provided a counted loop and GOTO forrepetition.

I Recursion was the foundation of LISP (List ProcessingLanguage, 1958), which had no loops and no GOTO.

I Both counted loops and recursion were present in ALGOL(1958, 1960).

I Other kinds of loops (while, do) developed much later.

Recursion and if...else are all you need to implement aprogramming language.

Page 22: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 22/40

What is a Recursive Function?

Procedural Thinking

I In a program with loops, the programmer starts with inputand a goal, and plans a series of steps to transform the inputinto the goal. Some of those steps involve loops.

I This is sequential thinking, sometimes called “proceduralthinking”. The focus of the thought is a procedure to achievethe goal, given the input.

I One can also solve problems using recursive thinking.

Page 23: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 23/40

What is a Recursive Function?

Recursive Thinking

Suppose you have a large problem to solve.

I Figure out how to break the problem into two or more parts insuch a way that the results can be combined to solve theoriginal problem.

I Figure out how to solve the problem for one or a few dataitems.

I Make sure that you can divide every large problem intosmaller problems that can eventually be reduced to the casefor a few items that you already know how to solve.

Page 24: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 24/40

What is a Recursive Function?

The Recursion Parameter(s)

One or more parameters to a recursive function define the size ofthe problem to be solved.

I A loop is infinite if the body of the loop does not change thevariable used in the exit test.

I An recursion is infinite if the exit test is never true becausethe recursion parameter(s) cycle or diverge or do not change.

I To write a correct recursion, you must ensure that the numberof unexplored possibilities decreases on each recursive call.

I Example: factorial decrements its parameter on each call.

I Example: the difference between two parameters of quicksortbecomes smaller on each call.

Page 25: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 25/40

What is a Recursive Function?

A Recursive Sorting Algorithm

Suppose you have a set of numbers (written on cards) to sort intointo ascending order (smallest on top).

I If there is one object in the set, it is sorted. Return the sortedcard to your boss. Sit down.

I If there are two to four objects in the set, sort them usinginsertion sort. Return the sorted cards to your boss. Sit down.

I Otherwise, divide your stack approximately in half, find twohelpers (they should stand up), and delegate sorting thehalves to them.

I Wait until both of your helpers return their sorted cards toyou. Merge the two stacks into one sorted stack. Return thestack to your boss. Sit down.

Page 26: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 26/40

How Does A Recursive Function Work?

I. How Does Recursion Work?

Function calls make stack frames.A recursive function calls itself.

Walking in and walking out of the recursion.

Page 27: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 27/40

How Does A Recursive Function Work?

Function calls make stack frames.

Modern programming languages use automatically allocateddynamic memory for function calls.

I Before a function is called, memory on the run-time stack isautomatically allocated in a block called a “stack frame”.

I The calling program stores the parameter values in this block.

I Then the hardware stores the return address and two stackpointers in the block.

I Space for the local variables follows the pointers. It isinitialized when control enters the function.

I Then the function’s code is executed.

I When the function returns, the stack frame is deallocated.

Page 28: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 28/40

How Does A Recursive Function Work?

A recursive function calls itself.

I When a function calls itself, the stack frame for the caller andthe stack frame for the called are BOTH on the stack.

I If recursive calls continue, many frames can existsimultaneously for successive invocations of the same function.

I The newest frame is always used as the context for execution.

I The older frames just wait on the stack until their “children”return and the “child” frames are deleted.

I Then the “parent” frame becomes active again.

unsigned factorial( unsigned n ) {

if (n < 2) return 1;

return n * factorial( n-1 );

}

Page 29: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 29/40

How Does A Recursive Function Work?

Stacking up the Frames: First Call

unsigned answer = factorial( 4 );

main ?answer

factorial4

main ?answer

nreturn address

2 pointers

Before the first call. After the first call.

Page 30: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 30/40

How Does A Recursive Function Work?

Stacking up the Frames: 2nd and 3rd Calls

After the second call.

factorial3n

return address2 pointers

factorial4

main ?answer

nreturn address

2 pointers

After the third call.

factorial2n

return address2 pointers

factorial3n

return address2 pointers

factorial4

main ?answer

nreturn address

2 pointers

Page 31: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 31/40

How Does A Recursive Function Work?

Stacking up the Frames: Last Call, First Return

factorial3n

return address2 pointers

factorial4

main ?

nreturn address

2 pointers

After the fourth call.

factorial2n

return address2 pointers

factorialn

return address2 pointers

1return 1

answer

factorial3n

return address2 pointers

factorial4

main ?

nreturn address

2 pointers

After the first return.

factorial2n

return address2 pointers

answer

return 2*1

Page 32: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 32/40

How Does A Recursive Function Work?

Stacking up the Frames: Finishing Up

factorial3n

return address2 pointers

factorial4

main ?

nreturn address

2 pointers

After the second return.

answer main 24

After the last return.

answer

return 3*2factorial

4

main ?

nreturn address

2 pointers

After the third return.

answer

return 4*6

Page 33: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 33/40

How Does A Recursive Function Work?

Walking in and walking out of the recursion.

Two kinds of things happen to the stack during a recursion:

I Stack frames are added as more recursive calls happen.

I Stack frames are removed when calls return.

In the factorial example, all the stack frames were created beforeanything was removed. However, this recursion is particularlysimple.

Many recursions (such as merge sort) add and remove, add andremove, in complex patterns.

Students generally find it easy to understand how and when stackframes are added. Some students have trouble with removing themone at a time and returning a value to the caller each time.

Page 34: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 34/40

Recursive Coding Patterns

I. Recursive Patterns

Linear tail recursion: sequential searchLinear recursion with post-processing: maximum

Non-linear tail recursions: Decision trees.Divide and Conquer: quicksort

Backtracking: Exhaustive search.

Page 35: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 35/40

Recursive Coding Patterns

Tail recursion: Sequential Search

A tail recursion is equivalent to a while loop and can easily berewritten as a loop.

I Only one recursive call is made on each activation.

I No processing is done after a “child” call returns – the answerreturned by the “child” is returned directly to the parent, andagain, up the line to the original caller.

I n is the number of values in the array; last value is at n-1.

int seqSearch( double ary[], int n, double key ) {

if (n<1) return -1;

if (ary[n-1]==key) return n-1;

return seqSearch( ary, n-1, key );

}

Page 36: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 36/40

Recursive Coding Patterns

Linear recursion that is not tail recursion: maximum

I Only one recursive call is made on each activation.

I The recursive call is NOT the last thing executed on eachrepetition.

I After a “child” call returns, the parent uses the return valueto compute something before returning to its caller.

// Return the subscript of the maximum element in the

array. int maximum( double ary[], int n ) {

if (n==1) return 0;

int temp = maximum( ary, n-1 );

return (ary[n-1] > ary[temp]) ? n-1 : temp ;

}

Page 37: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 37/40

Recursive Coding Patterns

Decision trees: Non-linear tail recursions.

I Two recursive calls appear in the code.

I However, only one recursive call is made on each activation.

int binSearch

(double ary[], int first, int last, double key)

{

if (last < first) return -1; // Search failed.

int mid = first + (last - first)/2;

if (ary[mid]==key) return mid; // Success.

if (ary[mid]>key) return

binSearch(ary, first, mid-1, key);

return binSearch( ary, mid+1, last, key );

}

Page 38: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 38/40

Recursive Coding Patterns

Divide and Conquer: quicksort

In practice, this is the fastest sorting algorithm for up to a coupleof thousand values.

I Split the array into two sections such that everything in theleft section is less than everything in the right section.

I Recursively sort each section.

I When a section is short (say below 20 items) stop usingrecursion and use insertion sort instead.

Refer to code file quick.c

Page 39: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 39/40

Recursive Coding Patterns

Backtracking

We do not know any efficient solution algorithm for some problems.

One way to solve such problems is to try all possible solutions.Backtracking is one way to search a space of possibilities.

I A partial solution is built incrementally.

I Each forward step reduces the number of untried possibilities.

I A partial solution is discarded when it becomes clear that itcannot be extended to a full solution.

I When that happens, control backtracks to the previous partialsolution (from which it was derived), from whence a differentway to progress is attempted.

Page 40: CSCI 2212: Intermediate Programming / C Recursioneliza.newhaven.edu/cprog2/attach/L9-recursion.pdf · 2015. 11. 16. · n 2 + c where c is a complex number (a point on the complex

. . . 40/40

Recursive Coding Patterns

Recursive exhaustive search (runmaze.c)We implement backtracking with a recursive function that tries thepossibilities.

I The parameter to the function specifies the current position inthe search space.

I The set of existing stack frames specifies the partial solution.

I On each activation, we try all possibile ways to progress,starting from the current position.

I If a possibility succeeds, it becomes the new position and thebasis for further exploration.

I If all of those possibilities fail, we backtrack, that is, we returnfrom the current stack frame to its “parent” frame.

I A position that has failed is never tried again.

I The process ends when we reach the goal or exhaust allpossibilities.