Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS148 Introduction to Programming II

Similar presentations


Presentation on theme: "CS148 Introduction to Programming II"— Presentation transcript:

1 CS148 Introduction to Programming II
Ayman Abdel-Hamid Department of Computer Science Old Dominion University Lecture 19: 4/14/2003 Lecture 19: 4/14/2003 CS148 Spring 2003

2 Outline Recursion Chapter 18 Lecture 19: 4/14/2003 CS148 Spring 2003

3 What is Recursion? A recursive definition is a definition in which something is defined in terms of smaller versions of itself YN = Y * Y * Y * ….* Y (Y multiplied by itself N times) YN = Y * (Y * Y * Y *…Y) (Y multiplied by itself N-1 times) YN = Y * YN-1 To calculate YN, multiply Y * by the value of YN-1 To calculate YN-1, multiply Y by the value of YN-2 We stop when N is equal to 1, since we know Y1-1 is Y0 = 1 The case for which an answer is explicitly known is called the base case A recursive algorithm is an algorithm that expresses the solution in terms of a call to itself, a recursive call. A recursive algorithm must terminate, i.e., it must have a base case Lecture 19: 4/14/2003 CS148 Spring 2003

4 A recursion example Power Function Power (2,3) Returns 8 x n 2 3
//calculates xn //n is assumed to be > 0 int Power (int x, int n) { if (n == 1) return x; // base case else return x* Power (x,n-1); // recursive call } Returns 8 x n 2 3 Call 1 Returns 4 x n 2 2 Call 2 Each recursive call to Power can be thought of as creating a completely new copy of the function, each with its own copies of the parameters x and n When a function is called, the computer system creates temporary storage for the parameters and the functions automatic local variables. This temporary storage is a region of memory called the run-time stack Returns 2 x n 2 1 Call 3 Lecture 19: 4/14/2003 CS148 Spring 2003

5 Another example The factorial of a number N (written N!) is N multiplied by N-1, N-2, N-3, and so on N! = N * (N-1)! 3!= 3*2*1 0! = 1 1! = 1 Factorial (3) Returns 6 //calculates n!, n assumed to be >= 0 int Factorial (int n) { if (n == 0 || n == 1) return 1; // base case else return n* Factorial (n-1); // recursive call } n 3 Call 1 Returns 2 n 2 Call 2 How to write a recursive algorithm? Identify the base case Identify the recursive case(s) Returns 1 n 1 Call 3 Lecture 19: 4/14/2003 CS148 Spring 2003

6 Yet Another Example Given the following input data (where \n denotes the newline character) ABCDE\n What is the output of the following program? (Question 10, page 1048, chapter 18) void main () { Rev(); } void Rev() char ch; cin.get (ch); if (ch != ‘\n’) cout << ch; Lecture 19: 4/14/2003 CS148 Spring 2003


Download ppt "CS148 Introduction to Programming II"

Similar presentations


Ads by Google