L29 L30 Recursive Functions
L29 L30 Recursive Functions
Objectives:
To learn and understand the following concepts:
• Understand recursion
• Write simple programs using recursive functions
▪Recursive steps:
▪ Identify the base case for the algorithm.
▪ Call the same function recursively with the parameter having slightly
modified value during each call.
▪ This makes the algorithm move towards the base case and finally
stop the recursion.
int fnSum(int x) {
if (x == 1) //base case
return 1;
else
return fnSum(x-1) + x; //recursive case
6/4/2022
} CSE 1001 Department of CSE 9
Factorial of a natural number–
a classical recursive example
So factorial(5)
= 5* factorial(4)
= 4* factorial(3)
= 3*factorial(2)
= 2* factorial(1)
= 1*factorial(0)
=1
6/4/2022 CSE 1001 Department of CSE 10
Factorial- recursive procedure
#include <stdio.h>
long factorial (long a) {
if (a ==0) //base case
return (1);
return (a * factorial (a-1)); Output:
} n=5
int main () { 5! = 120
long number;
printf("Please enter the number: “);
scanf(“%d”, &number);
printf(“%ld! = %ld”, number, factorial (number));
return 0;
}
x =24 = 120
5 rFact(4)
factorial(0) = 1
factorial(n) = n * factorial(n-1) [for n>0] 2
x
rFact(1) =1 = 2
x =24 = 120
5 rFact(4)
factorial(0) = 1
factorial(n) = n * factorial(n-1) [for n>0] 2
x
rFact(1) =1 = 2
Recursive Call:
1. Find the smallest element in the list and place it in the 0th position
2. Sort the unsorted array from 1.. n-1
sortR(&list[1], n-1)
{-2,33,0,2,4} sort(&list[1],4)
{-2,0,33,2,4} sort(&list[1],3)
{-2,0,2,33,4} sort(&list[1],2)
{-2,0,2,4,33} sort(&list[1],1)
• Pros • Cons
– Recursion is a natural fit – Recursive programs typically
for recursive problems use a large amount of
computer memory and the
greater the recursion, the
more memory used
– Recursive programs can be
confusing to develop and
extremely complicated to
debug
6/4/2022 CSE 1001 Department of CSE 24
Recursion vs Iteration
RECURSION ITERATION
Uses more storage space
Less storage space requirement
requirement
Overhead during runtime Less Overhead during runtime
• Definition
• Recursive functions