0% found this document useful (0 votes)
61 views

A Look Back at Functions: Recursion

The document discusses recursion and provides examples of calculating the factorial of a number recursively. It defines recursion as solving a problem by solving smaller instances of the same problem until a base case is reached. The example shows calculating 4! recursively by defining it as 4 * (4-1)! and then recursively calculating each smaller factorial down to the base cases of 1! and 0!.

Uploaded by

Ms Siam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views

A Look Back at Functions: Recursion

The document discusses recursion and provides examples of calculating the factorial of a number recursively. It defines recursion as solving a problem by solving smaller instances of the same problem until a base case is reached. The example shows calculating 4! recursively by defining it as 4 * (4-1)! and then recursively calculating each smaller factorial down to the base cases of 1! and 0!.

Uploaded by

Ms Siam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

A Look Back at Functions

#include <stdio.h>
#include <math.h>
double distance(double x1, double y1, double x2, double y2)
{
double dist;
dist = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
return dist;
}
int main()
{
double milage = distance(0, 0, 3, 4);
printf("Milage: %lf\n",milage);
return 0;

Lecture 11 }

Recursion
CSE115: Programming Language I

A Look Back at Functions A Look Back at Functions


#include <stdio.h> #include <stdio.h>
#include <math.h> #include <math.h>
double distance(double x1, double y1, double x2, double y2) double distance(double x1, double y1, double x2, double y2)
{ {
double dist; double dist;
dist = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); dist = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
return dist; return dist;
} }
int main() int main()
{ {
double milage = distance(0, 0, 3, 4); double milage = distance(0, 0, 3, 4);
printf("Milage: %lf\n",milage); printf("Milage: %lf\n",milage);
return 0; return 0;
} }

main main distance


(0,0,3,4)

3 4
A Look Back at Functions A Look Back at Functions
#include <stdio.h> #include <stdio.h>
#include <math.h> #include <math.h>
double distance(double x1, double y1, double x2, double y2) double distance(double x1, double y1, double x2, double y2)
{ {
double dist; double dist;
dist = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)); dist = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
return dist; return dist;
} }
int main() int main()
{ {
double milage = distance(0, 0, 3, 4); double milage = distance(0, 0, 3, 4);
printf("Milage: %lf\n",milage); printf("Milage: %lf\n",milage);
return 0; return 0;
} }

(5)

main distance sqrt main distance sqrt


(0,0,3,4) (25) (0,0,3,4) (25)

5 6

A Look Back at Functions Recursion


#include <stdio.h>
• Recursion is a technique that solves a problem by solving a smaller
#include <math.h> problem of the same type.
double distance(double x1, double y1, double x2, double y2)
{ • Recursion can be implemented using a recursive function (a
double dist;
dist = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
function invoking itself, either directly or indirectly).
}
return dist; • Recursion can be used as an alternative to iteration.
int main()
{
• It is an important and powerful tool in problem solving and
double milage = distance(0, 0, 3, 4); programming.
printf("Milage: %lf\n",milage);
return 0; • It is a programming technique that naturally implements the divide-
} and-conquer problem solving methodology.

(5)

main distance
(0,0,3,4)

7
Factorial – Iterative Definition Factorial – Recursive Definition
• To define n! recursively, n! must be defined in terms of
n! = n * (n-1) * (n-2) * … * 2 * 1 for any integer n>0 the factorial of a smaller number.
0! = 1 • Observation (problem size is reduced):
n! = n * (n-1)!
Iterative Definition in C: • Base case: 0! = 1
fval = 1; • We can reach the base case, by subtracting 1 from n if n
for (i = n; i >= 1; i--) is a positive integer.
fval = fval * i;
Recursive Definition:
n! = 1 if n = 0
n! = n*(n-1)! if n > 0

The Nature of Recursion Factorial of 4 (Recursive)


1. One or more simple cases of the problem (called the stopping cases or
base case) have a simple non-recursive solution.
Calculate 4!
2. The other cases (general cases) of the problem can be reduced (using 4! = 4 * (4-1)!
recursion) to problems that are closer to stopping cases. 4! = 4 * 3!
4! = 4 * __
3. Eventually the problem can be reduced to base cases only, which are
relatively easy to solve.

In general:
if (base case)
solve it
else
reduce the problem using recursion // general case
Factorial of 4 (Recursive) Factorial of 4 (Recursive)

Calculate 4! Calculate 4!
4! = 4 * (4-1)! 4! = 4 * (4-1)!
4! = 4 * 3! 4! = 4 * 3!
4! = 4 * __ Calculate 3! 4! = 4 * __ Calculate 3!
3! = 3 * (3-1)! 3! = 3 * (3-1)!
3! = 3 * 2! 3! = 3 * 2!
3! = 3 * __ 3! = 3 * __ Calculate 2!
2! = 2 * (2-1)!
2! = 2 * 1!
2! = 2 * __

Factorial of 4 (Recursive) Factorial of 4 (Recursive)

Calculate 4! Calculate 4!
4! = 4 * (4-1)! 4! = 4 * (4-1)!
4! = 4 * 3! 4! = 4 * 3!
4! = 4 * __ Calculate 3! 4! = 4 * __ Calculate 3!
3! = 3 * (3-1)! 3! = 3 * (3-1)!
3! = 3 * 2! 3! = 3 * 2!
3! = 3 * __ Calculate 2! 3! = 3 * __ Calculate 2!
2! = 2 * (2-1)! 2! = 2 * (2-1)!
2! = 2 * 1! 2! = 2 * 1!
2! = 2 * __ Calculate 1! 2! = 2 * __ Calculate 1!
1! = 1 * (1-1)! 1! = 1 * (1-1)!
1! = 1 * 0! 1! = 1 * 0!
1! = 1 * __ 1! = 1 * __
Calculate 0!
0! = 1
Factorial of 4 (Recursive) Factorial of 4 (Recursive)

Calculate 4! Calculate 4!
4! = 4 * (4-1)! 4! = 4 * (4-1)!
4! = 4 * 3! 4! = 4 * 3!
4! = 4 * __ Calculate 3! 4! = 4 * __ Calculate 3!
3! = 3 * (3-1)! 3! = 3 * (3-1)!
3! = 3 * 2! 3! = 3 * 2!
3! = 3 * __ Calculate 2! 3! = 3 * __ Calculate 2!
2! = 2 * (2-1)! 2! = 2 * (2-1)!
2! = 2 * 1! 2! = 2 * 1!
2! = 2 * __ Calculate 1! 2! = 2 * 1
1! = 1 * (1-1)! 2! = 2
1! = 1 * 0!
1! = 1 * 1
1! = 1

Factorial of 4 (Recursive) Factorial of 4 (Recursive)

Calculate 4! Calculate 4!
4! = 4 * (4-1)! 4! = 4 * (4-1)!
4! = 4 * 3! 4! = 4 * 3!
4! = 4 * __ Calculate 3! 4! = 4 * 6
3! = 3 * (3-1)! 4! = 24
3! = 3 * 2!
3! = 3 * 2
3! = 6
Recursive Factorial Function Tracing Factorial(4)
// Computes the factorial of a nonnegative integer.
Factorial(4)
// Precondition: n must be greater than or equal to 0.
// Postcondition: Returns the factorial of n; n is unchanged.

int Factorial(int n)
{
if (n ==0)
return (1);
else
return (n * Factorial(n-1));
}

Tracing Factorial(4) Tracing Factorial(4)


Factorial(4) Factorial(4) = 4 * Factorial(3)

call call

Factorial (4) Factorial (4)


call

Factorial (3)
Tracing Factorial(4) Tracing Factorial(4)
Factorial(4) = 4 * Factorial(3) Factorial(4) = 4 * Factorial(3)
= 4 * (3 * Factorial(2)) = 4 * (3 * Factorial(2))
= 4 * (3 * (2 * Factorial(1)))

call call

Factorial (4) Factorial (4)


call call

Factorial (3) Factorial (3)


call call

Factorial (2) Factorial (2)


call

Factorial (1)

Tracing Factorial(4) Tracing Factorial(4)


Factorial(4) = 4 * Factorial(3) Factorial(4) = 4 * Factorial(3)
= 4 * (3 * Factorial(2)) = 4 * (3 * Factorial(2))
= 4 * (3 * (2 * Factorial(1))) = 4 * (3 * (2 * Factorial(1)))
= 4 * (3 * (2 * (1 * Factorial(0)))) = 4 * (3 * (2 * (1 * Factorial(0))))
= 4 * (3 * (2 * (1 * 1)))
call call

Factorial (4) Factorial (4)


call call

Factorial (3) Factorial (3)


call call

Factorial (2) Factorial (2)


call call

Factorial (1) Factorial (1)


call call return 1

Factorial (0) Factorial (0)


Tracing Factorial(4) Tracing Factorial(4)
Factorial(4) = 4 * Factorial(3) Factorial(4) = 4 * Factorial(3)
= 4 * (3 * Factorial(2)) = 4 * (3 * Factorial(2))
= 4 * (3 * (2 * Factorial(1))) = 4 * (3 * (2 * Factorial(1)))
= 4 * (3 * (2 * (1 * Factorial(0)))) = 4 * (3 * (2 * (1 * Factorial(0))))
= 4 * (3 * (2 * (1 * 1))) = 4 * (3 * (2 * (1 * 1)))
= 4 * (3 * (2 * 1)) call
= 4 * (3 * (2 * 1)) call

Factorial (4) = 4 * (3 * 2) Factorial (4)


call call

Factorial (3) Factorial (3)


call call return 2*1 = 2

Factorial (2) Factorial (2)


call return 1*1 = 1 call return 1*1 = 1

Factorial (1) Factorial (1)


call return 1 call return 1

Factorial (0) Factorial (0)

Tracing Factorial(4) Tracing Factorial(4)


Factorial(4) = 4 * Factorial(3) Factorial(4) = 4 * Factorial(3)
= 4 * (3 * Factorial(2)) = 4 * (3 * Factorial(2))
= 4 * (3 * (2 * Factorial(1))) = 4 * (3 * (2 * Factorial(1)))
= 4 * (3 * (2 * (1 * Factorial(0)))) = 4 * (3 * (2 * (1 * Factorial(0))))
= 4 * (3 * (2 * (1 * 1))) = 4 * (3 * (2 * (1 * 1)))
= 4 * (3 * (2 * 1)) call
= 4 * (3 * (2 * 1)) call
return 4*6 = 24 final answer

= 4 * (3 * 2) Factorial (4) = 4 * (3 * 2) Factorial (4)


= 4 * 6 call return 3*2 = 6 = 4 * 6 call return 3*2 = 6

Factorial (3) Factorial (3)


= 24
call return 2*1 = 2 call return 2*1 = 2

Factorial (2) Factorial (2)


call return 1*1 = 1 call return 1*1 = 1

Factorial (1) Factorial (1)


call return 1 call return 1

Factorial (0) Factorial (0)


A Couple of Things You Should Know Pitfalls of Recursion
• If the recursion never reaches the base case, the recursive
calls will continue until the computer runs out of memory and
• A stack is used to keep track of function calls. the program crashes. Experienced programmers try to
• Whenever a new function is called, all its parameters examine the remains of a crash. The message “stack overflow
and local variables are pushed onto the stack along error” or “heap storage exhaustion” indicates a possible
runaway recursion.
with the memory address of the calling statement
(this gives the computer the return point after • When programming recursively, you need to make sure that
execution of the function) the algorithm is moving toward the base case. Each
successive call of the algorithm must be solving a simpler
version of the problem.
• Any recursive algorithm can be implemented iteratively, but
sometimes only with great difficulty. However, a recursive
solution will always run more slowly than an iterative one
because of the overhead of opening and closing the recursive
calls.

Fibonacci’s Problem Fibonacci’s Problem

“Fibonacci”
(Leonardo de Pisa)
1170-1240

35
Rabbit Rules Fibonacci’s Problem
1. All pairs of rabbits consist of a male and female How many pairs of rabbits will there be 12
2. One pair of newborn rabbits is placed in hutch on January 1 months later?
3. When this pair is 2 months old they produce a pair of baby
rabbits
4. Every month afterwards they produce another pair
5. All rabbits produce pairs in the same manner
6. Rabbits don’t die

37 38

0 2
Jan 1 Mar 1 0

1 3
Feb 1 Apr 1
1 0

4
2 May 1 2 1 0
Mar 1 0

40
3 1 0 In General,
Apr 1
4 2 1 0 0
May 1 Pairs this month
=
Pairs last month
+
Pairs of newborns

5 3 2 1 1 Pairs this month Pairs last month Pairs 2 months


June 1 = + ago

Fibonacci Numbers Fibonacci Numbers


int Fibonacci(int n)
{
if(n == 0)
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... return 0;
where each number is the sum of the preceding two. else if (n == 1)
return 1;
• Recursive definition: else
• F(0) = 0; return Fibonacci(n-1)+Fibonacci(n-2);
• F(1) = 1; }
• F(number) = F(number-1)+ F(number-2);

43
Fibonacci Numbers Fibonacci Numbers
int Fibonacci(int n) int Fibonacci(int n)
{ {
if(n == 0) if(n == 0)
return 0; return 0;
else if (n == 1) Base case else if (n == 1)
return 1; return 1;
else else
return Fibonacci(n-1)+Fibonacci(n-2); return Fibonacci(n-1)+Fibonacci(n-2);
} } General
case

Tracing Fibonacci(5) Another Example:


n choose r (combinations)
5 F(5)
Return F(4)+F(3)
3 2 • Given n things, how many different sets of size k can be
chosen?
F(4) F(3)
Return F(3)+F(2)
2 1 Return F(2)+F(1)
1 1 n n!
  = ,1 < r < n (closed form)
 r  r!×(n − r )!
F(3) F(2) F(2) F(1)
Return F(2)+F(1)
1 1 Return F(1)+F(0)
1 0 Return F(1)+F(0)
1 0 Return 1  n   n − 1  n − 1
  =   +  ,1 < r < n (recursive)
F(2) F(1) F(1) F(0) F(1) F(0)  r   r − 1  r 
Return F(1)+F(0)
1 0 Return 1 Return 1 Return 0 Return 1 Return 0 with base cases:
n n
F(1) F(0)   = n and   = 1
Return 1 Return 0 1 n
n choose r (Combinations) Tracing Combinations(4,3)

int Combinations(int n, int r)


{
if(r == 1) // base case 1
return n;
else if (n == r) // base case 2
return 1;
else //general case
return(Combinations(n-1, r-1) + Combinations(n-1, r));
}

Home-works
Implement the following function prototypes. You must implement them recursively.
• int sum(int n);
Description: Calculates the the sum 1 + 2 + ⋯ +
• void listNumbersAsc(int start, int end);
Description: Outputs the numbers from start to end in ascending order.
• void listNumbersDesc(int start, int end);
Description: Outputs the numbers from start to end in descending order.
• void printBinary(int x);
Description: Prints the binary equivalent of x.
• int mul(int a, int b);
Description: Returns the product of a and b. The only arithmetic operation that you are allowed to use in this
problem is addition (+).
• int power(int a, int b);
Description: Returns . The only arithmetic operation that you are allowed to use in this problem is
multiplication (*).
• double harmonicSum(int n);
Description: Returns the sum 1 + + + ⋯ + .
• int sumOfDigits(int x);
Description: Returns the sum of digits of the positive integer x. For example, when called with the parameter
12345, this function returns 15.

You might also like