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

L27 L28 Recursive Functions

The document discusses recursion, defining it as a technique that solves a problem by solving smaller versions of the same problem and outlines objectives to understand recursive algorithm design, solving problems recursively, and the relationship between recursion and iteration. It provides examples of recursively defined problems like factorials and Fibonacci numbers and explains the recursive process and steps to design a recursive algorithm, including identifying a base case and making recursive calls.

Uploaded by

Rugved Joshi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

L27 L28 Recursive Functions

The document discusses recursion, defining it as a technique that solves a problem by solving smaller versions of the same problem and outlines objectives to understand recursive algorithm design, solving problems recursively, and the relationship between recursion and iteration. It provides examples of recursively defined problems like factorials and Fibonacci numbers and explains the recursive process and steps to design a recursive algorithm, including identifying a base case and making recursive calls.

Uploaded by

Rugved Joshi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

RECURSION

L27-L28
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

11/06/2023 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

11/06/2023 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.
11/06/2023 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.
11/06/2023 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);
}
11/06/2023 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.

11/06/2023 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.

11/06/2023 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“); {
scanf(“%d”, n); if (x == 1) //base case
printf(“The sum is %d“,fnSum(n)); return 1;
return 0; else
} return x + fnSum(x-1) ;
//recursive case
}
int fnSum(int n){
int sum=0;
for(i=1;i<=n;i++)
sum=sum+i;
return (sum);
}

11/06/2023 CSE 1051 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

11/06/2023 CSE 1001 Department of CSE 10


Factorial- recursive procedure
#include <iostream>
using namespace std;
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;
}
11/06/2023 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
finished at the bottom --
x
It must unwind all the way back 4 rFact(3) = = 24
to the top in order to be done. 6

x = 6
3 rFact(2) =
2
factorial(0) = 1
factorial(n) = n * factorial(n-1) [for n>0] x = 2
2 rFact(1) =
long rFact (long a) { 1
if (a ==0)
return (1);
return (a * rFact (a-1)); x
} 1 rFact(0) = =1
1

CSE 1001 Department of CSE 11/06/2023 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
//1 1 2 3 5 8

11/06/2023 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

11/06/2023 CSE 1001 Department of CSE 14


Recursive Calls initiated by Fib(4)

11/06/2023 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;
}
11/06/2023 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( ); static int x = 0;


int main() {
int i; Output:
for( i= 1; i<=3; i++) void fnStat( ){
fnStat( ); x=1
static int x = 0;
return 0;
x = x + 1;
x=1
2
} x=1
3
printf(“x=%d”, x);
}

11/06/2023 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)
return (y);
if (y==0) gcd(9,24%9) gcd(9, 6)
return (x); gcd(6,9%6) gcd(6, 3)
return gcd(y, x % y); gcd(3,6%3) gcd(3, 0)
} return values return 3
return 3
return 3
return 3

Output:
x= 24 , y = 9
gcd = 3
11/06/2023 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

11/06/2023 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 Less elegant solution for


elegant solution for recursive problems
recursive problems

11/06/2023 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.

11/06/2023 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 -
scanf("%d%d", &a, &b); 1));
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

11/06/2023 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

11/06/2023 CSE 1001 Department of CSE 23


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

printf("Enter power number);


scanf("%d",&powerRaised);

result = power(base, powerRaised); Output:


Enter base number:3
printf("%d^%d = %d", base, powerRaised, result); Enter power number: 4
3^4=81
return 0;
}
11/06/2023 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);
}
11/06/2023 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
}
11/06/2023 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
11/06/2023 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;
if(num > 0)
int main() {
n = (n* 10) + (num%10) ;
int num;
printf(“enter number)”; else
scanf(“%d”,num); return n;
printf(“%d”, return rev(num/10);
rev(num)); } Output:
return 0; num = 234
} rev = 432

11/06/2023 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
11/06/2023 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;
11/06/2023 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 = (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 2 3 4 5
Enter the element to search: 3
} Element found at index : 2
11/06/2023 CSE 1001 Department of CSE 31
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

11/06/2023 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


11/06/2023 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[], int ln){ /* move smallest element to 0-th


element */
int i, tmp, min;
tmp = list[0];
if (ln == 1)
list[0] = list[min];
return 0;
list[min] = tmp;
/* find index of smallest no */
/* recursive call */
min = 0;
return sortR(&list[1], ln-
for(i = 1; i < ln; i++) 1);
if (list[i] < list[min]) }
Output:
min = i; Orign. array-: 33 -2 0 2 4
Sorted array -: -2 0 2 4 33

11/06/2023 CSE 1001 Department of CSE 34


Summary

• Definition

• Recursive functions

• Problems Solving Using Recursion

• Pros and Cons

• Recursive Vs Iterative Function

11/06/2023 CSE 1001 Department of CSE 35

You might also like