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

C Programming Recursion IIT

The document discusses recursion, a programming technique where a function calls itself to solve problems, often involving repetitive computations. It highlights the importance of base cases to prevent infinite loops and provides examples such as factorial, Fibonacci sequence, and combinations. The document also notes the pros and cons of recursion, emphasizing its readability and potential inefficiencies due to repeated computations.

Uploaded by

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

C Programming Recursion IIT

The document discusses recursion, a programming technique where a function calls itself to solve problems, often involving repetitive computations. It highlights the importance of base cases to prevent infinite loops and provides examples such as factorial, Fibonacci sequence, and combinations. The document also notes the pros and cons of recursion, emphasizing its readability and potential inefficiencies due to repeated computations.

Uploaded by

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

CS1101: Foundations of Programming

Recursion

Dept. of Computer Science & Engineering


Indian Institute of Technology Patna

IIT Patna 1
Recursion
• A process by which function calls itself repeatedly
• A function call itself directly or indirectly
• X calls X
• X calls Y, Y calls Z, Z calls X
• The process is used for repetitive computations
• Example: fact(n) = n * fact(n-1)
• Many iterative problems can be written in this form

IIT Patna 2
Base cases and Recursion
• As a function calls itself, we need some terminating condition. Otherwise, it
will be infinite loop
• Usually, a recursion will have two components.
• Base condition — stopping criteria
• Recursive step — repetitive computation step
• Example:
fact(n) = 1 if n = 0 // Stopping criteria
= n * fact(n-1) if n > 0 // Recursive step
• Usually, the stopping criteria is the scenario when we know the solution

IIT Patna 3
Examples
• Fibonacci sequence:

IIT Patna 4
Examples
• Fibonacci sequence:
Fib(0) = 0
Fib(1) = 1
Fib(n) = Fib(n-1)+Fib(n-2), if n>1

IIT Patna 4
Examples
• Fibonacci sequence:
Fib(0) = 0
Fib(1) = 1
Fib(n) = Fib(n-1)+Fib(n-2), if n>1
• Combination:

IIT Patna 4
Examples
• Fibonacci sequence:
Fib(0) = 0
Fib(1) = 1
Fib(n) = Fib(n-1)+Fib(n-2), if n>1
• Combination:
ncr(n,n) = 1
ncr(n,0) = 1
ncr(n,r) = ncr(n-1,r)+ncr(n-1,r-1), if n>r>0

IIT Patna 4
Examples
• Fibonacci sequence:
Fib(0) = 0
Fib(1) = 1
Fib(n) = Fib(n-1)+Fib(n-2), if n>1
• Combination:
ncr(n,n) = 1
ncr(n,0) = 1
ncr(n,r) = ncr(n-1,r)+ncr(n-1,r-1), if n>r>0
• GCD: assuming m ≥n

IIT Patna 4
Examples
• Fibonacci sequence:
Fib(0) = 0
Fib(1) = 1
Fib(n) = Fib(n-1)+Fib(n-2), if n>1
• Combination:
ncr(n,n) = 1
ncr(n,0) = 1
ncr(n,r) = ncr(n-1,r)+ncr(n-1,r-1), if n>r>0
• GCD: assuming m ≥n
gcd(m,0) = m
gcd(m,n) = gcd(n,m%n), in n>0

IIT Patna 4
Example: Factorial
int fact(int n){
if(n == 1){
return 1;
} else {
return (n * fact(n-1));
}
}

IIT Patna 5
Recursion flow: Factorial
fact(4)

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

IIT Patna 6
Recursion flow: Factorial
fact(4)

if(4 == 1) return(1);
else return(4*fact(3));

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

IIT Patna 6
Recursion flow: Factorial
fact(4)

if(4 == 1) return(1);
else return(4*fact(3));

if(3 == 1) return(1);
else return(3*fact(2));

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

IIT Patna 6
Recursion flow: Factorial
fact(4)

if(4 == 1) return(1);
else return(4*fact(3));

if(3 == 1) return(1);
else return(3*fact(2));

if(2 == 1) return(1);
int fact(n){
else return(2*fact(1));
if(n==1) return(1);
else return(n*fact(n-1));
}

IIT Patna 6
Recursion flow: Factorial
fact(4)

if(4 == 1) return(1);
else return(4*fact(3));

if(3 == 1) return(1);
else return(3*fact(2));

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

IIT Patna 6
Recursion flow: Factorial
fact(4)

if(4 == 1) return(1);
else return(4*fact(3));

if(3 == 1) return(1);
else return(3*fact(2));

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

IIT Patna 6
Recursion flow: Factorial
fact(4)

if(4 == 1) return(1);
else return(4*fact(3));

if(3 == 1) return(1);
else return(3*fact(2)); 2

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

IIT Patna 6
Recursion flow: Factorial
fact(4)

if(4 == 1) return(1);
else return(4*fact(3)); 6

if(3 == 1) return(1);
else return(3*fact(2)); 2

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

IIT Patna 6
Recursion flow: Factorial
24
fact(4)

if(4 == 1) return(1);
else return(4*fact(3)); 6

if(3 == 1) return(1);
else return(3*fact(2)); 2

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

IIT Patna 6
Fibonacci sequence
• Fibonacci sequence: F0 = 0, F1 = 1, Fn = Fn−1 + Fn−2
• Sequence: 0,1,1,2,3,5,8,13,21,…
• Recursive code:
int fib(n){
if(n<2) return n;
else return (fib(n-1)+fib(n-2));
}

IIT Patna 7
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2));
}

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2));
}
f(3)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2));
}
f(3)

f(2)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2));
}
f(3)

f(2)

f(1)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2));
}
f(3)

f(2)
1

f(1)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2));
}
f(3)

f(2)
1

f(1) f(0)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2));
}
f(3)

f(2)
1 0

f(1) f(0)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2));
}
f(3)
1

f(2)
1 0

f(1) f(0)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2));
}
f(3)
1

f(2) f(1)
1 0

f(1) f(0)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2));
}
f(3)
1 1

f(2) f(1)
1 0

f(1) f(0)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2)); 2
}
f(3)
1 1

f(2) f(1)
1 0

f(1) f(0)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2)); 2
}
f(3) f(2)
1 1

f(2) f(1)
1 0

f(1) f(0)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2)); 2
}
f(3) f(2)
1 1

f(2) f(1) f(1)


1 0

f(1) f(0)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2)); 2
}
f(3) f(2)
1 1 1

f(2) f(1) f(1)


1 0

f(1) f(0)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2)); 2
}
f(3) f(2)
1 1 1

f(2) f(1) f(1) f(0)


1 0

f(1) f(0)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2)); 2
}
f(3) f(2)
1 1 1 0

f(2) f(1) f(1) f(0)


1 0

f(1) f(0)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2)); 2 1
}
f(3) f(2)
1 1 1 0

f(2) f(1) f(1) f(0)


1 0

f(1) f(0)

IIT Patna 8
Recursion flow: Fibonacci
int f(int n){ 3
if(n<2) return(n);
f(4)
else return (f(n-1)+f(n-2)); 2 1
}
f(3) f(2)
How many f() calls are there for f(4)? 9 1 1 1 0

f(2) f(1) f(1) f(0)


1 0

f(1) f(0)

Inefficiency arises due to repeated computation of the same things

IIT Patna 8
Notes
• Every recursion program can also be written without recursion
• Easy to replace tail recursion by a loop
• In general, removal of recursion may be a difficult task
• Recursion can be helpful in many solutions
• Better readability, Ease of programming
• Sometime, recursion gives best-possible or best known algorithms to solve
problems
• Recursion can also be a killer
• You solve the same subproblem multiple times
• Every recursive call incurs a small overhead
• Use recursion carefully

IIT Patna 9
Things to remember
• Think how the current problem can be solved if you can solve exactly the same
problem on one or more smaller instances
• Do not think how the smaller problem will be solved, just call the function
recursively assume that the recursive calls do the job correctly
• Do not forget to include base cases to solve the smallest instance
• This is similar to mathematical induction
• To write recursive function make sure of the following
• First write the base condition (terminating step)
• Write the rest of the part of the function

IIT Patna 10
Example: Print the digits of an integer in reverse
• If the input is 2860 then you need to print 0682
• Use recursion to do this

IIT Patna 11
Example: Print the digits of an integer in reverse
• If the input is 2860 then you need to print 0682
• Use recursion to do this

void printReverse(int j){


if(j < 10){
printf("%d",j);
} else {
printf("%d",j%10);
printReverse(j/10);
}
}

IIT Patna 11
Print your name in reverse
#include <stdio.h>
void printReverse(){
char c;
scanf("%c",&c);
if(c == '\n')
return;
printReverse();
printf("%c",c);
}

int main(){
printf("Enter your name:");
printReverse();
printf("\n");
return 0;
}

IIT Patna 12
Print your name in reverse
#include <stdio.h>
void printReverse(){
char c; Output:
scanf("%c",&c); Enter your name:Doris Ursula
if(c == '\n') alusrU siroD
return;
printReverse();
printf("%c",c);
}

int main(){
printf("Enter your name:");
printReverse();
printf("\n");
return 0;
}

IIT Patna 12
Print your name in reverse
#include <stdio.h>
void printReverse(){
char c; Output:
scanf("%c",&c); Enter your name:Doris Ursula
if(c == '\n') alusrU siroD
return;
printReverse();
Modify the code to have following output:(Homework)
printf("%c",c);
Enter your name:Doris Ursula
}
Name in reverse:alusrU siroD
int main(){
printf("Enter your name:");
printReverse();
printf("\n");
return 0;
}

IIT Patna 12
Tower of Hanoi
• Problem:
• There are three pegs and 8 circular disks.
• Each disk has a different size and a smaller disk can rest on a larger disk
• At a time only one disk can be moved from one peg to the other
• What is the minimum number of moves required?
• How many moves will be required when the number of disk is 64? How much
time will it take to execute?
• Known as Tower of Brahma

A B C
IIT Patna 13
Tower of Hanoi - 1
• Moves when there is 1 disk

A B C

IIT Patna 14
Tower of Hanoi - 1
• Moves when there is 1 disk

A B C

IIT Patna 14
Tower of Hanoi - 2
• Moves when there are 2 disks

A B C

IIT Patna 15
Tower of Hanoi - 2
• Moves when there are 2 disks

A B C

IIT Patna 15
Tower of Hanoi - 2
• Moves when there are 2 disks

A B C

IIT Patna 15
Tower of Hanoi - 2
• Moves when there are 2 disks

A B C

IIT Patna 15
Tower of Hanoi
• Problem:
• What is the strategy to move n disks? How many moves will be required when
the number of disk is n?

A B C

IIT Patna 16
Tower of Hanoi
• Problem:
• What is the strategy to move n disks? How many moves will be required when
the number of disk is n?

A B C

IIT Patna 16
Tower of Hanoi
• Problem:
• What is the strategy to move n disks? How many moves will be required when
the number of disk is n?

A B C

IIT Patna 16
Tower of Hanoi
• Problem:
• What is the strategy to move n disks? How many moves will be required when
the number of disk is n?

A B C

IIT Patna 16
Tower of Hanoi - 3
• Moves when there are 3 disks

A B C

IIT Patna 17
Tower of Hanoi - 3
• Moves when there are 3 disks

A B C

Move A to C

IIT Patna 17
Tower of Hanoi - 3
• Moves when there are 3 disks

A B C

Move A to C
Move A to B

IIT Patna 17
Tower of Hanoi - 3
• Moves when there are 3 disks

A B C

Move A to C
Move A to B
Move C to B

IIT Patna 17
Tower of Hanoi - 3
• Moves when there are 3 disks

A B C

Move A to C
Move A to B
Move C to B
Move A to C

IIT Patna 17
Tower of Hanoi - 3
• Moves when there are 3 disks

A B C

Move A to C
Move A to B
Move C to B
Move A to C
Move B to A

IIT Patna 17
Tower of Hanoi - 3
• Moves when there are 3 disks

A B C

Move A to C
Move A to B
Move C to B
Move A to C
Move B to A
Move B to C

IIT Patna 17
Tower of Hanoi - 3
• Moves when there are 3 disks

A B C

Move A to C
Move A to B
Move C to B
Move A to C
Move B to A
Move B to C
Move A to C

IIT Patna 17
Tower of Hanoi
#include <stdio.h>
void toh(int n, char F, char T, char A);
int main(){
int n;
scanf("%d",&n);
toh(n,'A','C','B');
}
void toh(int, char F, char T, char A){
if(n>0){
toh(n-1, F, A, T);
printf("Move disk %d from %c to %c\n",n,F,T);
toh(n-1, A, T, F);
}
}
IIT Patna 18
Common mistakes
• No base cases
• Terminating condition is never reached

IIT Patna 19
Common mistakes
• No base cases
• Terminating condition is never reached

int fact(int n){


return n*fact(n-1);
}

IIT Patna 19
Common mistakes
• No base cases
• Terminating condition is never reached

int fact(int n){ int func1(int n){


return n*fact(n-1); if(n==1) return 1;
} return func1(n--);
}

IIT Patna 19
Common mistakes
• No base cases
• Terminating condition is never reached

int fact(int n){ int func1(int n){


return n*fact(n-1); if(n==1) return 1;
} return func1(n--);
}

int func2(int n){


if(n==0) return 1;
return n*(n-1)*func2(n-2);
}

IIT Patna 19
Common mistakes
• No base cases
• Terminating condition is never reached

int fact(int n){ int func1(int n){


return n*fact(n-1); if(n==1) return 1;
} return func1(n--);
}

int func2(int n){


if(n==0) return 1;
return n*(n-1)*func2(n-2);
}
Base condition will not be reached for odd n

IIT Patna 19
Recursion vs Iteration
• Common features
• Both achieve repetition
• Both have some terminating conditions, execution gradually approaches ter-
mination
• Both can have infinite loop
• Issues
• Recursion has overhead of function call
• Many problems do not require recursive solutions
• Implementation / Readability is for recursion usually
• You need to take an educated decision

IIT Patna 20
Data storage
int fact(int n){
int val;
if(n==1) return 1;
val = n * fact(n-1);
printf("n: %lu,%d val: %lu,%d\n",&n,n,&val,val);
return val;
}

int main(){
int n=5;
fact(n);
}

IIT Patna 21
Data storage
int fact(int n){
int val;
if(n==1) return 1;
val = n * fact(n-1);
printf("n: %lu,%d val: %lu,%d\n",&n,n,&val,val);
return val;
} Output:
n: 140731046224636,2 val: 140731046224644,2
int main(){ n: 140731046224684,3 val: 140731046224692,6
int n=5; n: 140731046224732,4 val: 140731046224740,24
fact(n); n: 140731046224780,5 val: 140731046224788,120
}

IIT Patna 21
What will be the output?
void func(int n){
int d;
if(n==0) return;
scanf("%d",&d);
func(n-1);
printf("%d\n",d);
}

int main(){
int n=5;
func(n);
}

IIT Patna 22
What will be the output?
void func(int n){ void func(int n){
int d; int d;
if(n==0) return; if(n==0) return;
scanf("%d",&d); func(n-1);
func(n-1); scanf("%d",&d);
printf("%d\n",d); printf("%d\n",d);
} }

int main(){ int main(){


int n=5; int n=5;
func(n); func(n);
} }

IIT Patna 22
What will be the output?
void func(int n){ void func(int n){ void func(int n){
int d; int d; int d;
if(n==0) return; if(n==0) return; if(n==0) return;
scanf("%d",&d); func(n-1); scanf("%d",&d);
func(n-1); scanf("%d",&d); printf("%d\n",d);
printf("%d\n",d); printf("%d\n",d); func(n-1);
} } }

int main(){ int main(){ int main(){


int n=5; int n=5; int n=5;
func(n); func(n); func(n);
} } }

IIT Patna 22
What will be the output?
int func(int n){
int s;
if(n==0) return 0;
s = n + func(n-1);
printf("%d\n",s);
return s;
}

int main(){
int n=5;
func(n);
}

IIT Patna 23
What will be the output?
int func(int n){
int s;
if(n==0) return 0;
s = n + func(n-1); Output:
printf("%d\n",s); 1
return s; 3
} 6
10
int main(){ 15
int n=5;
func(n);
}

IIT Patna 23
What will be the output?
int func(int n){
int sum,d;
if(n==0) return 0;
scanf("%d",&d);
sum = func(n-1);
sum += d;
printf("%d\n",sum);
return sum;
}

int main(){
int n=5;
func(n);
}
IIT Patna 24
What will be the output?
int func(int n){
void func(int n,int sum){
int sum,d;
int d;
if(n==0) return 0;
if(n==0) return;
scanf("%d",&d);
scanf("%d",&d);
sum = func(n-1);
sum += d;
sum += d; Input:
printf("%d\n",sum);
printf("%d\n",sum); 12345
func(n-1,sum);
return sum; Output: ?
}
}

int main(){
int main(){
int n=5;
int n=5;
func(n,0);
func(n); }
}
IIT Patna 24
What will be the output?
int func(int n, int m){
if(n==1) return m;
else return (m + func(n-1, m));
}

int main(){
int n=13, m=5, out;
out = func(n, m);
}

IIT Patna 25
What will be the output?
int func(int n, int m){
if(n==1) return m;
else return (m + func(n-1, m));
}

int main(){
int n=13, m=5, out;
out = func(n, m);
}

Multiplication using repeated sum

IIT Patna 25
Largest element in the array

int max(int x[], int low, int size){


int large;
if(low == size) return x[low-1];
large = max(x, low+1, size);
return large > x[low-1] ? large : x[low-1];
}

IIT Patna 26
Largest element in the array

int max(int x[], int low, int size){


int large;
if(low == size) return x[low-1];
large = max(x, low+1, size);
return large > x[low-1] ? large : x[low-1];
}

Intuition: Find the largest element (m) from 2 to n, then compare m with
the first element and determine largest for 1 to n

IIT Patna 26
Largest element in the array

int max(int x[], int l, int h){


int m, maxl, maxr;
if(l == h) return x[l];
maxl = max(x, l, (l+h)/2);
maxr = max(x, (l+h)/2+1, h);
return maxl > maxr ? maxl : maxr ;
}

IIT Patna 27
Largest element in the array

int max(int x[], int l, int h){


int m, maxl, maxr;
if(l == h) return x[l];
maxl = max(x, l, (l+h)/2);
maxr = max(x, (l+h)/2+1, h);
return maxl > maxr ? maxl : maxr ;
}

Intuition: Find the largest on the first half (m1 ), then on the second half
(m2 ), and then return the maximum of m1 and m2

IIT Patna 27
Memory: Function call
int main(){ int fact(int x){
.
. .
.
. .
.
.
x = fact(n); .
.
.
. return value;
} }

{
Activation
{

Local variables
MEMORY

z }|
record
Return value
Return addr
STACK
z }|

Before call After call After return


IIT Patna 28
Memory: Function call

int main(){ int npr(int n, int r){ int fact(int x){


.
. .
. .
.
. . .
.
. .
.
x = fact(n, r); . .
.
.
. return fact(n)/fact(r); return value;
} } }

RA, RV, LV - fact


RA, RV, LV - npr RA, RV, LV - npr RA, RV, LV - npr

Before call After npr call After fact call After fact return After return

IIT Patna 29
Practice problems
• Write a recursive function to find an element in an array
• Write a recursive function that prints the binary equivalent of a integer number
• Write a recursive function to find sum of the squares of a set of integers stored in an array
• Write a recursive function to copy one array to another
• Write a recursive function to determine xn , x - float, n - int

IIT Patna 30

You might also like