Attribution Non-Commercial (BY-NC)

10 views

Attribution Non-Commercial (BY-NC)

- Procedure to Create the Memory Game
- A First Principles Derivation of Functional Derivatives
- AndroidNetrunner v2.1 rules cheat sheet
- Binary Trees
- SolidWorks Menus Toolbars
- Possible Algorithms of 2NF and 3NF for DBNorma- A tool for Relational Database Normalization
- 07 DS and Algorithm Session 10
- EE3751 Microprocessor Laboratory Summer 2009
- Intro Touch Sensors
- ChapteFl: Ar;Thmetic and Geometric Series
- MemoizationWithCorrection
- Data Structures
- Notes 14
- What is Data Structure
- Lab 3
- Algorithmic and Problem Solving
- recursion1
- Unit Planning Reflection
- unit planning reflection
- Qs and Ans

You are on page 1of 48

Objectives

In this chapter you will: Learn about recursive definitions Explore the base case and the general case of a recursive definition Discover what is a recursive algorithm Learn about recursive functions Explore how to use recursive functions to implement recursive algorithms

C++ Programming: From Problem Analysis to Program Design, Second Edition 2

a recursive call is a function call in which the called function is the same as the one making the call in other words, recursion occurs when a function calls itself! but we need to avoid making an infinite sequence of function calls (infinite recursion)

a recursive solution to a problem must be written carefully the idea is for each successive recursive call to bring you one step closer to a situation in which the problem can easily be solved this easily solved situation is called the base case each recursive algorithm must have at least one base case, as well as a general (recursive) case

if (some easily-solved condition) solution statement else recursive function call // general case // base case

SOME EXAMPLES . . .

5

DISCUSSION The function call Summation(4) should have value 10, because that is 1 + 2 + 3 + 4 . For an easily-solved situation, the sum of the numbers from 1 to 1 is certainly just 1. So our base case could be along the lines of if ( n == 1 ) return 1;

Now for the general case. . . The sum of the numbers from 1 to n, that is, 1 + 2 + . . . + n can be written as n + the sum of the numbers from 1 to (n - 1), that is, n + 1 + 2 + . . . + (n - 1) or, n + Summation(n - 1)

And notice that the recursive call Summation(n - 1) gets us closer to the base case of Summation(1)

int Summation ( /* in */ int n ) // Computes the sum of the numbers from 1 to n by // adding n to the sum of the numbers from 1 to (n-1) // Precondition: n is assigned && n > 0 // Postcondition: // Function value == sum of numbers from 1 to n { // base case if ( n == 1) return 1 ; else // general case return ( n + Summation ( n - 1 ) ) ; }

8

Call 1:

Summation(4)

n 4

Returns 4 + Summation(3) = 4 + 6 = 10

Returns 3 + Summation(2) = 3 + 3 = 6

Call 2:

Summation(3)

n 3

Returns 2 + Summation(1)

Call 3:

Summation(2)

n 2

=2+1= 3

n==1

Returns 1

Call 4:

Summation(1)

n 1

DISCUSSION The function call Factorial(4) should have value 24, because that is 4 * 3 * 2 * 1 . For a situation in which the answer is known, the value of 0! is 1. So our base case could be along the lines of if ( number == 0 ) return 1;

10

Now for the general case . . . The value of Factorial(n) can be written as n * the product of the numbers from (n - 1) to 1, that is, n * (n - 1) * . . . * 1 or, n * Factorial(n - 1)

And notice that the recursive call Factorial(n - 1) gets us closer to the base case of Factorial(0).

11

Recursive Solution

int Factorial ( int number ) // Pre: number is assigned and number >= 0. { if ( number == 0) // base case return 1 ; // general case else return number * Factorial ( number - 1 ) ; }

12

void PrintStars ( /* in */ int n )

// Prints n asterisks, one to a line // Precondition: n is assigned // Postcondition: // IF n > 0, n stars have been printed, one to a line // ELSE no action has taken place { if ( n <= 0 ) // base case // Do nothing else // general case { cout << << endl ; PrintStars ( n - 1 ) ; } }

// CAN REWRITE AS . . .

13 13

void PrintStars ( /* in */ int n )

// Prints n asterisks, one to a line // Precondition: n is assigned // Postcondition: // IF n > 0, n stars have been printed, one to a line // ELSE no action has taken place

{ if ( n > 0 ) // general case { cout << << endl ; PrintStars ( n - 1 ) ; } // base case is empty else-clause }

14

14

Call 1:

PrintStars(3)

n 3 Call 2:

PrintStars(2)

* is printed n 2 Call 3:

PrintStars(1)

* is printed

* is printed

n 1 Call 4:

PrintStars(0) Do nothing

n 0

15

DISCUSSION For this task, we will use the prototype: void PrintRev( const int data[ ], int first, int last );

6000

74

data[0]

36

data[1]

87

95

data[2] data[3]

95

87

36 74

16

A base case may be a solution in terms of a smaller array. Certainly for an array with 0 elements, there is no more processing to do. Now our general case needs to bring us closer to the base case situation. That is, the length of the array to be processed decreases by 1 with each recursive call. By printing one element in the general case, and also processing the smaller array, we will eventually reach the situation where 0 array elements are left to be processed. In the general case, we could print either the first element, that is, data[first]. Or we could print the last element, that is, data[last]. Lets print data[last]. After we print data[last], we still need to print the remaining elements in reverse order.

17

void PrintRev ( /* in */ const int data [ ] , // Array to be printed /* in */ int first , // Index of first element /* in */ int last ) // Index of last element // Prints array elements data [ first. . . last ] in reverse order // Precondition: first assigned && last assigned // && if first <= last then data [first . . last ] assigned { // general case if ( first <= last ) { // print last element cout << data [ last ] << ; PrintRev ( data, first, last - 1 ) ; // then process the rest } // Base case is empty else-clause }

18

18

PrintRev(data, 0, 2) Trace

Call 1:

first 0 PrintRev(data, 0, 2) last 2

data[2] printed

Call 2:

PrintRev(data, 0, 1) data[1] printed

first 0 last 1

Call 3:

PrintRev(data, 0, 0) data[0] printed

first 0 last 0

Call 4:

NOTE: data address 6000 is also passed PrintRev(data, 0, -1) Do nothing

first 0 last -1

19

Recursive Functions

You can have: One base case and one recursive case An empty (does nothing) base case Multiple base cases Multiple recursive cases But you MUST always have a base case (even if it does nothing) to avoid infinite recursion

C++ Programming: From Problem Analysis to Program Design, Second Edition 20

These examples could all have been written without recursion, by using iteration instead. The iterative solution uses a loop, and the recursive solution uses an if statement. However, for certain problems the recursive solution is the most natural solution. This often occurs when data structures (for example, linked lists, trees) are used.

21

For certain problems the recursive solution is the most natural solution. This often occurs when pointer variables are used. For example: print the nodes of a linked list in reverse order

22

struct NodeType

struct NodeType { char NodeType* } NodeType* head ;

component ; link ;

23

RevPrint(head);

head A B C D E

FIRST, print out this section of list, backwards THEN, print this element

24

Recall that . . .

recursion occurs when a function calls itself (directly or indirectly) recursion can be used in place of iteration (looping) some functions can be written more easily using recursion

25

Recursion or Iteration?

CLARITY

EFFICIENCY

26

Iteration: efficient (faster, minimum memory requirement) Recursion: For some problems, simpler to write and understand than the iterative version However for a problem requiring deep recursion you may run out of memory, or it may take an extremely long time to run

27

a transfer of control occurs from the calling block to the code of the function--it is necessary that there be a return to the correct place in the calling block after the function code is executed; this correct place is called the return address when any function is called, the run-time stack is used-on this stack is placed an activation record for the function call

28

the activation record contains the return address for this function call, and also the parameters, and local variables, and space for the functions return value, if non-void the activation record for a particular function call is popped off the run-time stack when the final closing brace in the function code is reached, or when a return statement is reached in the function code at this time the functions return value, if non-void, is brought back to the calling block return address for use there

29

// Another recursive function int Func ( /* in */ int a, /* in */ int b ) // Pre: Assigned(a) && Assigned(b) // Post: Function value == ?? { int result; if ( b == 0 ) result = 0; else if ( b > 0 ) // first general case // base case

result = a + Func ( a , b - 1 ) ; // instruction 50 else // second general case result = Func ( - a , - b ) ; // instruction 70

return result; }

30

30

x = Func(5, 2); // original call at instruction 100

? ? 2 5 100

31

x = Func(5, 2); // original call at instruction 100

? ? 1 5 50 ? 5+Func(5,1) = ? 2 5 100

32

x = Func(5, 2);

FCTVAL result b a Return Address FCTVAL result b a Return Address FCTVAL result b a Return Address

? ? 0 5 50 ? 5+Func(5,0) = ? 1 5 50 ? 5+Func(5,1) = ? 2 5 100

33

x = Func(5, 2);

FCTVAL result b a Return Address FCTVAL result b a Return Address FCTVAL result b a Return Address

0 0 0 5 50 ? 5+Func(5,0) = ? 1 5 50 ? 5+Func(5,1) = ? 2 5 100

34

x = Func(5, 2); // original call at instruction 100

FCTVAL 5 result 5+Func(5,0) = 5+ 0 b 1 a 5 Return Address 50 FCTVAL result b a Return Address ? 5+Func(5,1) = ? 2 5 100

35

x = Func(5, 2); // original call at instruction 100

36

Towers of Hanoi

The Towers of Hanoi problem is an example of a problem that is easy to solve with recursion, difficult to solve with iteration

37

Tower of Hanoi

The rules for moving disks are as follows:

Only one disk can be moved at a time The removed disk must be placed on one of the needles A larger disk cannot be placed on top of a smaller disk

39

This recursive algorithm translates into the following C++ function:

40

Programming Example

Use recursion to convert a non-negative integer in decimal format (base 10) into the equivalent binary number (base 2) Define some terms:

Let x be an integer The remainder of x after division by 2 is the rightmost bit of x The rightmost bit of 33 is 1 because 33 % 2 is 1 The rightmost bit of 28 is 0 because 28 % 2 is 0

C++ Programming: From Problem Analysis to Program Design, Second Edition 42

To find the binary representation of 35

Divide 35 by 2 The quotient is 17 and the remainder is 1 Divide 17 by 2 The quotient is 8 and the remainder is 1 Divide 8 by 2 The quotient is 4 and the remainder is 0 Continue this process until the quotient becomes 0

C++ Programming: From Problem Analysis to Program Design, Second Edition 43

The rightmost bit of 35 cannot be printed until we have printed the rightmost bit of 17 The rightmost bit of 17 cannot be printed until we have printed the rightmost bit of 8, and so on

44

The binary representation of 35 is the binary representation of 17 (the quotient of 35 after division by 2) followed by the rightmost bit of 35

binary(num) = num if num = 0 binary(num) = binary(num/2) followed by num%2 if num > 0

45

Summary

The process of solving a problem by reducing it to smaller versions of itself is called recursion A function is called recursive if it calls itself Every recursive definition has one or more base cases The solution to the problem in a base case is obtained directly

47

Summary

The general case must eventually be reduced to a base case The base case stops the recursion

48

- Procedure to Create the Memory GameUploaded byInderpartap Cheema
- A First Principles Derivation of Functional DerivativesUploaded byNicholas Fisk
- AndroidNetrunner v2.1 rules cheat sheetUploaded byiprunner
- Binary TreesUploaded byblack Snow
- SolidWorks Menus ToolbarsUploaded bysnagareddy
- 07 DS and Algorithm Session 10Uploaded byAshish Srivastava
- EE3751 Microprocessor Laboratory Summer 2009Uploaded bypnahuy
- Intro Touch SensorsUploaded bylabstudent
- Possible Algorithms of 2NF and 3NF for DBNorma- A tool for Relational Database NormalizationUploaded byIDES
- ChapteFl: Ar;Thmetic and Geometric SeriesUploaded byMathathlete
- MemoizationWithCorrectionUploaded byshobhit007
- Data StructuresUploaded byBrunall_Kate
- Notes 14Uploaded byمحمد شزرين
- What is Data StructureUploaded byRanjetha Segar
- Lab 3Uploaded byMagdalene Heuk Salvatore
- Algorithmic and Problem SolvingUploaded byĐông Lai
- recursion1Uploaded byDinesh Khandelwal
- Unit Planning ReflectionUploaded bymaiselke
- unit planning reflectionUploaded byapi-211388817
- Qs and AnsUploaded byrsprmails
- Soc PresentationUploaded byAnonymous JPbUTto8tq
- Leon County Curve EvaluationsUploaded byBilal Saghir
- AP GP SummaryUploaded byPng Poh Sheng
- Codeforces ComUploaded byZulqarnayn
- cseb114_courseoutlineUploaded byTan YK
- Lecture 25and26 Fall17Uploaded byHassan Abbas
- Function and Recursion of pythonUploaded bySaicharanSai
- c programming begineer.docxUploaded byPankaj Kumar
- A Flowchart to generate CodeUploaded byshu2u
- les_02.txtUploaded byarturodvs

- MushroomUploaded bySamuel Davis
- Heap Leach DesignUploaded byustav
- Mems AssignmentUploaded bysrishag
- IT 461 Final Course ProjectUploaded byEric Gabrielle
- Guide to the Systems Engineering Body of KnowledgeUploaded byGeorge Schiro
- media1Uploaded byAbhishek Singh
- Guidance Equations for LaunchUploaded byedkyle99
- MG6HK WE 0221Manual MotorUploaded byWilliam Giovanni Madariaga Malebrán
- Uml Lab Manual (1)Uploaded by7killers4u
- Booking File HistoryUploaded byAnsari Fahad Anis
- 3parUploaded bysanju_81
- Structural Fire Design according to EurocodesUploaded byHenry
- Boysaw v Interphil PromotionsUploaded byKenneth Peter Molave
- 1002 (2)Uploaded byBalu Mahendra Susarla
- Hcd-d90av-Gr10av-Rx100avUploaded bysoptik_cz
- Research on Child LabourUploaded byAbubakar Gafar
- Pepsi HistoryUploaded bykannan2009
- EQ L7 BMS Assignment 2 NewOct15Uploaded byfmartin
- Prior criminal indictments against Corey GaynorUploaded byPenn Buff Network
- probaUploaded byIvan Antunovic
- Organisational Theory Structure and Design - Assignment September 2017 j0i4OLiccqUploaded byPrasanth Kumar
- Coroguide LinkUploaded byDulis Dulis
- SKG Bontang Risk & Secuirty ManagementUploaded byWiwis Arie
- Sdsdsd.htmlUploaded byjaarit
- comcast on demand remote manualUploaded byEd McManus
- What Have We Really Learned? Twenty Five Years After Piper Alpha, 2015, Process Safety ProgressUploaded byjeremyg998
- pistola Daisy 717Uploaded byDiego Ruesch
- Bulletin Dec13eUploaded byRantharu Attanayake
- Medication Error TypesUploaded byKamalakar Karamcheti
- Riello Multiplus Ups Series 100 120 ManualUploaded byJorgeErnestoCartagena

## Much more than documents.

Discover everything Scribd has to offer, including books and audiobooks from major publishers.

Cancel anytime.