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

32-Function Recursion

The document provides an overview of recursion, including its definition, benefits, and drawbacks compared to iteration. It explains how to design recursive algorithms, presents examples such as factorial and Fibonacci numbers, and discusses the importance of base cases. Additionally, it includes various programming problems that can be solved using recursion.

Uploaded by

anshulshah216
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

32-Function Recursion

The document provides an overview of recursion, including its definition, benefits, and drawbacks compared to iteration. It explains how to design recursive algorithms, presents examples such as factorial and Fibonacci numbers, and discusses the importance of base cases. Additionally, it includes various programming problems that can be solved using recursion.

Uploaded by

anshulshah216
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

RECURSION

Objectives:
To learn and understand the following concepts:

 To design a recursive algorithm


 To solve problems using recursion
 To understand the relationship and difference between
recursion and iteration

05/16/2025 CSE 1001 Department of CSE 2


Session outcome:
At the end of session one will be able to :

• Understand recursion
• Write simple programs using recursive functions

05/16/2025 CSE 1001 Department of CSE 3


What is Recursion ?
• Sometimes, the best way to solve a problem is by solving a smaller
version of the exact same problem first.

• Recursion is a technique that solves a problem by solving a smaller


problem of the same type.

• A recursive function is a function that invokes / calls itself directly or


indirectly.

• In general, code written recursively is shorter and a bit more


elegant, once you know how to read it.

• It enables you to develop a natural, straightforward, simple solution


to a problem that would otherwise be difficult to solve.
05/16/2025 CSE 1001 Department of CSE 4
What is Recursion ?
 Mathematical problems that are recursive in nature like factorial,
fibonacci, exponentiation, GCD, Tower of Hanoi, etc. can be easily
implemented using recursion.

 Every time when we make a call to a function, a stack frame is


allocated for that function call where all the local variables in the
functions are stored. As recursion makes a function to call itself
many times till the base condition is met, many stack frames are
allocated and it consumes too much main memory and also makes
the program run slower.

 We must use recursion only when it is easy and necessary to use,


because it take more space and time compared to iterative
approach.
05/16/2025 CSE 1001 Department of CSE 5
Let us consider the code …
int main() {
int i, n, sum=0;
printf("Enter the limit“);
scanf(“%d”,n);
printf("The sum is %d“,fnSum(n));
return 0;
}
int fnSum(int n){
int sum=0;
for(i=1;i<=n;i++)
sum=sum+i;
return (sum);
05/16/2025 CSE 1001
}
Department of CSE 6
Recursive Thinking …..
Recursion Process

A child couldn't sleep, so her mother told a story about a little frog,
who couldn't sleep, so the frog's mother told a story about a little
bear,
who couldn't sleep, so bear's mother told a story about a little
weasel
...who fell asleep.
...and the little bear fell asleep;
...and the little frog fell asleep;
...and the child fell asleep.

05/16/2025 CSE 1001 Department of CSE 7


Steps to Design a Recursive Algorithm
 Base case:
 It prevents the recursive algorithm from running forever.

 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.

05/16/2025 CSE 1001 Department of CSE 8


Let us consider same code again …
int main() {
int i, n, sum=0; int fnSum(int x) {
printf("Enter the limit“); if (x == 1) //base case
scanf(“%d”, n);
return 1;
printf(“The sum is %d“,fnSum(n));
return 0; else
} return x + fnSum(x-1) ;

int fnSum(int n){ //recursive


int sum=0; case
for(i=1;i<=n;i++) }
sum=sum+i;
return (sum);
}
05/16/2025 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)
05/16/2025 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));
}
int main () {
long number;
printf("Please type a number: “);
scanf(“%d”, number);
printf(“number ! = %d”, factorial (number));
return 0;
}

05/16/2025 CSE 1001 Department of CSE 11


Recursion - How is it doing!
rFact(5) 120

x =2 = 120
5 rFact(4)
4
Notice that the
recursion isn’t x
finished at the 4 rFact(3) = = 24
6
bottom --
It must unwind all x =
3 rFact(2) = 6
the way back to the
2
top in order to be
factorial(0) = 1
done.
factorial(n) = n * 2
x
rFact(1) = = 2
factorial(n-1) [for n>0] 1

long rFact (long a) {


if (a ==0) 1
x
rFact(0) = =1
return (1); 1
return (a * rFact (a-1));
}
CSE 1001 Department of CSE 05/16/2025 12
Fibonacci Numbers: Recursion
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(n) = fibonacci(n-1) + fibonacci(n-2) [for n>1]

So fibonacci(4)
= fibonacci(3) + fibonacci(2)
= (fibonacci(2) + fibonacci(1)) + (fibonacci(1) + fibonacci(0))
= ((fibonacci(1) + fibonacci(0)) + 1) + (1 + 0)
= ( 1 + 0 ) + 1) + (1 + 0)
=3

05/16/2025 CSE 1001 Department of CSE 13


Fibonacci Numbers: Recursion
Fibonacci series is 0,1, 1, 2, 3, 5, 8 …
int rfibo(int n)
{
if (n <= 1)
return n;
else
return (rfibo(n-1) + rfibo(n-2));
}
Output:
n=4
fib = 3

05/16/2025 CSE 1001 Department of CSE 14


Recursive Calls initiated by Fib(4)

05/16/2025 CSE 1001 Department of CSE 15


Fibonacci Series using Recursion
int rfibo(int);

int main(void){
int n,i, a[20], fibo;
printf("enter any num to n\n“);
scanf(“%d”, n);
printf(“Fibonacci series “);
for (i=1; i<=n; i++)
{
fibo = rfibo(i);
printf(“%d”, fibo);
}
return 0;
}
05/16/2025 CSE 1001 Department of CSE 16
Static Variable:
The value of static variable persists until the end of the
program.
Static variables can be declared as
static int x;
A static variable can be either an internal or external
type depending on the place of declaration.

void fnStat( );
Output:
int main() { void fnStat( ){ x=1
int i; static int
static intx x==0;0; x=1 2
for( i= 1; i<=3; x = x + 1; x=1 3
i++) printf(“x=%d”,
fnStat( ); x);
05/16/2025 return 0; }
CSE 1001 Department of CSE 17
GCD: Recursion

int gcd(int x, int y)


{ gcd(24,9)  Control In gcd fn on call
if (x == 0) gcd(9,24%9) gcd(9, 6)
return (y); gcd(6,9%6) gcd(6, 3)
if (y==0) gcd(3,6%3) gcd(3, 0)
return (x); return values return 3
return 3
return gcd(y, x % y); return 3
} return 3

Output:
x= 24 , y = 9
gcd = 3
05/16/2025 CSE 1001 Department of CSE 18
Recursion - Should I or Shouldn’t I?

• Pros • Cons
– Recursion is a – Recursive programs
natural fit for typically use a large
recursive problems 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

05/16/2025 CSE 1001 Department of CSE 19


Recursion vs Iteration

RECURSION ITERATION

Uses more storage space Less storage space


requirement requirement

Overhead during runtime Less Overhead during


runtime

Runs slower Runs faster


A better choice, a more
elegant solution for Less elegant solution for
recursive problems recursive problems

05/16/2025 CSE 1001 Department of CSE 20


Recursion – Do’s
• You must include a termination condition or Base
Condition in recursive function; Otherwise your
recursive function will run “forever” or infinite.
• Each successive call to the recursive function must be
nearer to the base condition.

05/16/2025 CSE 1001 Department of CSE 21


Extra Problem- Finding product of two numbers
#include <stdio.h> int product(int a, int b)
{
int product(int, int); if (a < b)
int main() {
return product(b, a);
{
}
int a, b, result; else if (b != 0)
printf("Enter two numbers to find their product: "); {
return (a + product(a, b - 1));
scanf("%d%d", &a, &b); }
result = product(a, b); else
{
printf("%d * %d = %d\n", a, b, result); return 0;
return 0; }
}
}
Output:
Enter two numbers to find their product: 10
20
10*20=200
05/16/2025 CSE 1001 Department of CSE 22
Extra Problem- Dividing two numbers
#include <stdio.h> int divide(int a, int b)
int divide(int a, int b); {
if(a - b <= 0)
{
int main() return 1;
{ }
else
int a,b; {
return divide(a - b, b) + 1;
printf("Enter two numbers for division"); }
}
scanf("%d%d", &a,&b);
printf("%d/%d=%d",a,b,divide(a,b));
return 0;
} Output:
Enter two numbers for division: 20 10
20/10=2

05/16/2025 CSE 1001 Department of CSE 23


Extra Problem- Calculating power of a number
#include <stdio.h> int power(int base, int powerRaised)
int power(int n1, int n2); {
if (powerRaised != 0)
return (base*power(base, powerRaised-1));
int main()
else
{ return 1;
int base, powerRaised, result; }

printf("Enter base number: ");


scanf("%d",&base);

printf("Enter power number);


scanf("%d",&powerRaised);
Output:
result = power(base, powerRaised); Enter base number:3
Enter power number: 4
printf("%d^%d = %d", base, powerRaised, result); 3^4=81

return 0;
}
05/16/2025 CSE 1001 Department of CSE 24
Extra Problem- Sum of natural numbers
#include <stdio.h> int sum(int num)
int sum(int n); {
if (num!=0)
return num + sum(num-1);
int main()
else
{ return num;
int number, result; }

printf("Enter a positive integer: ");


scanf("%d", &number);
Output:
result = sum(number); Enter a positive integer: 10
Sum= 55

printf("sum=%d", result);
}
05/16/2025 CSE 1001 Department of CSE 25
Extra Problem- To count number of digits
#include <stdio.h>
int countDigits(int num)
int countDigits(int);
{
int main() static int count=0;
{
int number; if(num>0)
int count=0; {
count++;
printf("Enter a positive integer number: "); countDigits(num/10);
}
scanf("%d",&number);
else
{
count=countDigits(number); return count;
}
printf(“Number of digits is: %d\n",count); }
Output:
return 0; Enter a positive integer number: 123
Number of digits is: 3
}
05/16/2025 CSE 1001 Department of CSE 26
Extra Problem- To find sum of all digits
#include <stdio.h>
int sumDigits(int num)
int sumDigits(int num); {
int main() static int sum=0;
{ if(num>0)
int number,sum; {
sum+=(num%10);
sumDigits(num/10);
printf("Enter a positive integer number: ");
}
scanf("%d",&number); else
{
sum=sumDigits(number); return sum;
}
printf("Sum of all digits are: %d\n",sum); }
Output:
return 0; Enter a positive integer number: 123
} Number of digits is: 3
05/16/2025 CSE 1001 Department of CSE 27
Extra Problem-Reversing a Number

#include <stdio.h> int rev(int num){


int rev(int); static int n = 0;
int main() { if(num > 0)
int num; n = (n* 10) + (num%10) ;
printf(“enter else
number)”;
return n;
scanf(“%d”,num);
printf(“%d”, return rev(num/10);
rev(num)); } Output:
return 0; num = 234
} rev = 432

05/16/2025 CSE 1001 Department of CSE 28


Extra Problem- To find length of a string

#include <stdio.h>
int length(char [], int); int length(char str[], int index)
{
int main()
if (str[index] == '\0')
{
char str[20]; {
int count; return 0;
}
printf("Enter any string :: "); return (1 + length(str, index + 1));
scanf("%s", str); }
count = length(str, 0);
printf("The length of string=%d.\n",count);
return 0;
Output:
}
Enter any string :: Manipal
The length of string= 7
05/16/2025 CSE 1001 Department of CSE 29
Extra Problem-Binary Search
#include<stdio.h>
int binarySearch(int x[],int element,int start,int end);
int main(){
int x[20],n,i,index,start=0,end,element;
printf("Enter number of elements: ");
scanf("%d",&n);
end = n;
printf("Enter array elements: ");
for(i=0;i<n;i++){
scanf("%d",&x[i]);
}
printf("Enter the element to search: ");
scanf("%d",&element);
index = binarySearch(x,element,start,end-1);
if(index == -1)
printf("Element Not Found.\n");
else
printf("Element found at index : %d\n",index);
return 0;
05/16/2025 CSE 1001 Department of CSE 30
}
Extra Problem-Binary Search
int binarySearch(int x[],int element,int start,int end){
int mid,noOfElements,i;
mid = (int)(start+end)/2;
if(start > end)
return -1;
if(x[mid] == element)
return mid;
else if(x[mid] < element){
start = mid+1;
binarySearch(x,element,start,end);
}
else{
start = 0;
end = mid-1; Output:
binarySearch(x,element,start,end); Enter number of
} elements: 5
Enter array elements: 1
2345
} Enter the element to
search: 3
05/16/2025 CSE 1001 Department of CSE 31
Element found at
Extra Problem- Recursive Sorting
Base Case:
if length of the list (n) = 1
No sorting, return

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)

For eg: list [ ] = {33,-2,0,2,4} n=5

05/16/2025 CSE 1001 Department of CSE 32


Extra problem-Sorting

list[] function calls


{33,-2,0,2,4} sort(list,5) Main()

{-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)

Base case reached .... Return


05/16/2025 CSE 1001 Department of CSE 33
Extra problem - Sorting
sortR(list, n);// call of fn & display of sorted array in
main()
int sortR(int list[], /* move smallest element
to 0-th element */
int ln){
tmp = list[0];
int i, tmp, min;
list[0] = list[min];
if (ln == 1)
list[min] = tmp;
return 0;
/* recursive call */
/* find index of smallest no
*/ return
min = 0; sortR(&list[1], ln-
for(i = 1; i < ln; i++) 1);
Output:
if (list[i] < }
Orign. array-: 33 -2
0 2 4
list[min]) Sorted array -: -2 0
2 4 33
05/16/2025
min = i; CSE 1001 Department of CSE 34

You might also like