SlideShare a Scribd company logo
1 of 66
Recursion
Functions – reminder
A function can call other functions.
Return causes the execution of the function to
terminate and returns a value to the calling
function.
The type of the value returned must be the same
as the return-type defined for the function.
return-type name(argType1 arg1, argType2 arg2, …) {
function body;
return value;
}
A recursive definition
C functions can also call themselves!
 However, usually not with the same parameters
(why?)
Some functions can be defined using
smaller occurrences of themselves.
Such a definition is called a “recursive
definition” of a function.
Recursive calling
Example:
void func(int n){
putchar(`*`);
func(n);
}
Infinite series of *
What is the problem ?
Look for other problem …
Factorial
By definition :
n! = 1*2*3*… *(n-1)*n
Thus, we can also define factorial the following way:
 0! = 1
 n! = n*(n-1)! for n>0
(n-1)! *n
Example - factorial
int factRec(int n){
if (n==0 || n==1)
return 1;
return n*factRec(n-1);
}
int factorial(int n){
int fact = 1;
while (n >= 1) {
fact *=n;
n--;
}
return fact;
}
Conclusions for Recursive calling
Every recursive function has a “boundary
condition”. The function stops calling itself when it
is satisfied.
Recursive factorial – step by step
int factRec(int n)
{
if (n==0 || n==1)
return 1;
return n*factRec(n-1);
}
FactRec(4)
n
4
Returns…
Recursive factorial – step by step
int factRec(int n)
{
if (n==0 || n==1)
return 1;
return n*factRec(n-1);
}
FactRec(4)
n
4
Returns…
4*…
Recursive factorial – step by step
int factRec(int n)
{
if (n==0 || n==1)
return 1;
return n*factRec(n-1);
}
FactRec(4)
n
4
Returns…
FactRec(3)
n
3
Returns…
Recursive factorial – step by step
int factRec(int n)
{
if (n==0 || n==1)
return 1;
return n*factRec(n-1);
}
FactRec(4)
n
4
Returns…
FactRec(3)
n
3
Returns…
Recursive factorial – step by step
int factRec(int n)
{
if (n==0 || n==1)
return 1;
return n*factRec(n-1);
}
FactRec(4)
n
4
Returns…
FactRec(3)
n
3
Returns…
3*…
Recursive factorial – step by step
int factRec(int n)
{
if (n==0 || n==1)
return 1;
return n*factRec(n-1);
}
FactRec(4)
n
4
Returns…
FactRec(3)
n
3
Returns…
FactRec(2)
n
2
Returns…
Recursive factorial – step by step
int factRec(int n)
{
if (n==0 || n==1)
return 1;
return n*factRec(n-1);
}
FactRec(4)
n
4
Returns…
FactRec(3)
n
3
Returns…
FactRec(2)
n
2
Returns…
Recursive factorial – step by step
int factRec(int n)
{
if (n==0 || n==1)
return 1;
return n*factRec(n-1);
}
FactRec(4)
n
4
Returns…
FactRec(3)
n
3
Returns…
FactRec(2)
n
2
Returns…
2*…
Recursive factorial – step by step
int factRec(int n)
{
if (n==0 || n==1)
return 1;
return n*factRec(n-1);
}
FactRec(4)
n
4
Returns…
FactRec(3)
n
3
Returns…
FactRec(2)
n
2
Returns…
FactRec(1)
n
1
Returns…
Recursive factorial – step by step
int factRec(int n)
{
if (n==0 || n==1)
return 1;
return n*factRec(n-1);
}
FactRec(4)
n
4
Returns…
FactRec(3)
n
3
Returns…
FactRec(2)
n
2
Returns…
FactRec(1)
n
1
Returns…
Recursive factorial – step by step
int factRec(int n)
{
if (n==0 || n==1)
return 1;
return n*factRec(n-1);
}
FactRec(4)
n
4
Returns…
FactRec(3)
n
3
Returns…
FactRec(2)
n
2
Returns…
FactRec(1)
n
1
Returns…
1
Recursive factorial – step by step
int factRec(int n)
{
if (n==0 || n==1)
return 1;
return n*factRec(n-1);
}
FactRec(4)
n
4
Returns…
FactRec(3)
n
3
Returns…
FactRec(2)
n
2
Returns…
2*1
Recursive factorial – step by step
int factRec(int n)
{
if (n==0 || n==1)
return 1;
return n*factRec(n-1);
}
FactRec(4)
n
4
Returns…
FactRec(3)
n
3
Returns…
3*2
Recursive factorial – step by step
int factRec(int n)
{
if (n==0 || n==1)
return 1;
return n*factRec(n-1);
}
FactRec(4)
n
4
Returns…
4*6
1
#include <stdio.h>
void print1(int n){
if (n>=0){
printf("%d ",n);
print1(n-1);
{
{
void main(){
int i = 3;
print1(i);
putchar('n');
{
3 2 1 0
2
#include <stdio.h>
void print2(int n){
if (n>=0){
print2(n-1);
printf("%d ",n);
{
{
void main(){
int i = 3;
print2(i);
putchar('n');
{
0 1 2 3
3
#include <stdio.h>
void print3(int n){
if (n>=0){
printf("%d ",n);
print3(n-1);
printf("%d ",n);
{
{
void main(){
int i = 3;
print3(i);
putchar('n');
{
3 2 1 0 0 1 2 3
4
#include <stdio.h>
void print4(int n){
if (n>=0){
print4(n-1);
printf("%d ",n);
print4(n-1);
{
{
void main(){
int i = 3;
print4(i);
putchar('n');
{
0 1 0 2 0 1 0 3 0 1 0 2 0 1 0
Another example - power
 X
y
= x*x*…*x
 Recursive definitions (assume non-negative y):
 Base: x0
=1
1. X
y
= X*(X
y-1
)
2. X
y
=(X
y/2
)
2
(for even y’s only)
y times
Fibonacci Series
Fibonacci definition:
 n0 = 0
 n1 = 1
 nn = nn-1 + nn-2
0 1 1 2 3 5 8 13 21 34 55 …
Fibonacci Iterative
void fibonacci(int n) {
int Fn, Fn1, Fn2, ind;
Fn2 = 0 ;
Fn1 = 1 ;
Fn = 0 ;
if ( n == 1 )
Fn = 1 ;
for (ind=2 ; ind <= n ; ind++){
Fn = Fn1 + Fn2;
Fn2 = Fn1;
Fn1 = Fn;
}
printf("F(%d) = %d n", n, Fn);
}
Fibonacci Recursive
fibonacci(1)
fibonacci(5)
fibonacci(4) fibonacci(3)
fibonacci(3) fibonacci(2) fibonacci(2)
fibonacci(1)
fibonacci(2) fibonacci(1) fibonacci(1)
fibonacci(0)
fibonacci(0) fibonacci(1) fibonacci(0)
int fibonacci(int n) {
if (n==0)
return 0;
if (n==1)
return 1;
return fibonacci(n-1) + fibonacci(n-2);
}
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
2*…
y
5
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
y
4
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
y
4
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
y
4
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(…)
y
4
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(…)
y
4
rec_pow(2, 2)
x
2
Returns…
y
2
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(…)
y
4
rec_pow(2, 2)
x
2
Returns…
y
2
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(…)
y
4
rec_pow(2, 2)
x
2
Returns…
y
2
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(…)
y
4
rec_pow(2, 2)
x
2
Returns…
square(…)
y
2
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(…)
y
4
rec_pow(2, 2)
x
2
Returns…
square(…)
y
2
rec_pow(2, 1)
x
2
Returns…
y
1
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(…)
y
4
rec_pow(2, 2)
x
2
Returns…
square(…)
y
2
rec_pow(2, 1)
x
2
Returns…
y
1
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(…)
y
4
rec_pow(2, 2)
x
2
Returns…
square(…)
y
2
rec_pow(2, 1)
x
2
Returns…
y
1
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(…)
y
4
rec_pow(2, 2)
x
2
Returns…
square(…)
y
2
rec_pow(2, 1)
x
2
Returns…
y
1
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(…)
y
4
rec_pow(2, 2)
x
2
Returns…
square(…)
y
2
rec_pow(2, 1)
x
2
Returns…
2*…
y
1
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(…)
y
4
rec_pow(2, 2)
x
2
Returns…
square(…)
y
2
rec_pow(2, 1)
x
2
Returns…
2*…
y
1
rec_pow(2, 0)
x
2
Returns…
y
0
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(…)
y
4
rec_pow(2, 2)
x
2
Returns…
square(…)
y
2
rec_pow(2, 1)
x
2
Returns…
2*…
y
1
rec_pow(2, 0)
x
2
Returns…
y
0
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(…)
y
4
rec_pow(2, 2)
x
2
Returns…
square(…)
y
2
rec_pow(2, 1)
x
2
Returns…
2*…
y
1
rec_pow(2, 0)
x
2
Returns…
1
y
0
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(…)
y
4
rec_pow(2, 2)
x
2
Returns…
square(…)
y
2
rec_pow(2, 1)
x
2
Returns…
2*1
y
1
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(…)
y
4
rec_pow(2, 2)
x
2
Returns…
square(2)
y
2
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
y
5
rec_pow(2, 4)
x
2
Returns…
square(4)
y
4
rec_pow – step by step
int rec_pow(int x, int y)
{
if (y == 0)
return 1;
if (y%2 == 0)
return square(rec_pow(x,y/2));
else
return x*rec_pow(x,y-1);
}
rec_pow(2, 5)
x
2
Returns…
2*16
y
5
Exercise
Write a program that receives two non-negative
integers and computes their product recursively.
Not * multiple operator !!
Hint: Notice that the product a*b is actually a+a+…
+a (b times).
Solution
int recMult( int x, int y ) {
if( x == 0)
return 0;
return y + recMult( x-1,y);
{
Exercise
Given the following iterative
version of
sum-of-digits calculation
Find the recursive definition
of this function
(don’t forget the base case!)
int sum_digits(int n){
int sum = 0;
while (n > 0) {
sum += n%10;
n = n/10;
}
return sum;
}
Solution
int sumOfDigits( int x ) {
if( x < 0)
x *= -1;
if( x == 0 )
return 0;
else
return x % 10 + sumOfDigits( x / 10 );
}
More uses
Recursion is a general approach to programming
functions.
Its uses are not confined to calculating mathematical
expressions!
For example : write a function that finds the max
member in an array of integer.
Solution
int rec_max(int arr[ ], int size){
int rest;
if (size == 1)
return arr[0];
else {
rest = rec_max(arr+1, size-1);
if (arr[0] > rest)
return arr[0];
else
return rest;
}
}
int BinarySearch(int arr[],int x, int left, int right) {
int middle;
if(left>right)
return -1;
else {
middle=(left+right)/2);
if(arr[middle]==x)
return middle;
else if(x < arr[middle])
return BinarySearch(arr,x,left,middle-1);
else return BinarySearch(arr,x,middle+1,right);
}
}
Towers of Hanoi
The Towers of Hanoi problem consists of three rods,
and a number of disks of different sizes which can slide
onto any rod. The puzzle starts with the disks in a neat
stack in ascending order of size on one rod, the smallest at
the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to
another rod, obeying the following rules:
 Only one disk may be moved at a time.
 Each move consists of taking the upper disk from one of
the rods and sliding it onto another rod, on top of the
other disks that may already be present on that rod.
 No disk may be placed on top of a smaller disk.
Towers of Hanoi
Recursive Solution
To move n disks from peg A to peg C:
 move n−1 disks from A to B. This leaves disk #n
alone on peg A
 move disk #n from A to C
 move n−1 disks from B to C so they sit on disk #n
Recursive Solution - Function
void hanoi(int x, char from, char to, char aux){
if(x==1){
printf("Move Disk From %c to %cn", from, to);
}
else {
hanoi(x-1,from,aux,to);
printf("Move Disk From %c to %cn", from, to);
hanoi(x-1,aux,to,from);
}
}
Scope of variables - reminder
A variable declared within a function is
unrelated to variables declared
elsewhere.
A function cannot access variables that
are declared in other functions.

More Related Content

What's hot

functions
 functions  functions
functions
Gaditek
 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2
chidabdu
 

What's hot (20)

Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0Let Us Learn Lambda Using C# 3.0
Let Us Learn Lambda Using C# 3.0
 
Recursion(Advanced data structure)
Recursion(Advanced data structure)Recursion(Advanced data structure)
Recursion(Advanced data structure)
 
Lecture09 recursion
Lecture09 recursionLecture09 recursion
Lecture09 recursion
 
CPSC 125 Ch 2 Sec 4
CPSC 125 Ch 2 Sec 4CPSC 125 Ch 2 Sec 4
CPSC 125 Ch 2 Sec 4
 
Primitive Recursive Functions
Primitive Recursive FunctionsPrimitive Recursive Functions
Primitive Recursive Functions
 
functions
 functions  functions
functions
 
5.2 primitive recursive functions
5.2 primitive recursive functions5.2 primitive recursive functions
5.2 primitive recursive functions
 
Asymptotic Notation
Asymptotic NotationAsymptotic Notation
Asymptotic Notation
 
01. design & analysis of agorithm intro & complexity analysis
01. design & analysis of agorithm intro & complexity analysis01. design & analysis of agorithm intro & complexity analysis
01. design & analysis of agorithm intro & complexity analysis
 
Mathematical Analysis of Recursive Algorithm.
Mathematical Analysis of Recursive Algorithm.Mathematical Analysis of Recursive Algorithm.
Mathematical Analysis of Recursive Algorithm.
 
Induction
InductionInduction
Induction
 
Algorithm.ppt
Algorithm.pptAlgorithm.ppt
Algorithm.ppt
 
Advanced C - Part 3
Advanced C - Part 3Advanced C - Part 3
Advanced C - Part 3
 
Control System Homework Help
Control System Homework HelpControl System Homework Help
Control System Homework Help
 
6-Python-Recursion.pdf
6-Python-Recursion.pdf6-Python-Recursion.pdf
6-Python-Recursion.pdf
 
Divide and Conquer
Divide and ConquerDivide and Conquer
Divide and Conquer
 
Algorithm chapter 2
Algorithm chapter 2Algorithm chapter 2
Algorithm chapter 2
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and ScalaFolding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala
 
Arrays
ArraysArrays
Arrays
 
Functions
FunctionsFunctions
Functions
 

Similar to Recursion

Lecture 4 - Growth of Functions (1).ppt
Lecture 4 - Growth of Functions (1).pptLecture 4 - Growth of Functions (1).ppt
Lecture 4 - Growth of Functions (1).ppt
ZohairMughal1
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
Eelco Visser
 

Similar to Recursion (20)

14 recursion
14 recursion14 recursion
14 recursion
 
Recursion
RecursionRecursion
Recursion
 
Sec4
Sec4Sec4
Sec4
 
6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx6-Python-Recursion PPT.pptx
6-Python-Recursion PPT.pptx
 
Ds0601 stack
Ds0601 stackDs0601 stack
Ds0601 stack
 
Recursion.pdf
Recursion.pdfRecursion.pdf
Recursion.pdf
 
Presentation 6 (1).pptx
Presentation 6 (1).pptxPresentation 6 (1).pptx
Presentation 6 (1).pptx
 
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
High Order Function Computations in c++14 (C++ Dev Meetup Iasi)
 
Finite elements : basis functions
Finite elements : basis functionsFinite elements : basis functions
Finite elements : basis functions
 
06 Recursion in C.pptx
06 Recursion in C.pptx06 Recursion in C.pptx
06 Recursion in C.pptx
 
Lecture 4 - Growth of Functions (1).ppt
Lecture 4 - Growth of Functions (1).pptLecture 4 - Growth of Functions (1).ppt
Lecture 4 - Growth of Functions (1).ppt
 
Lecture 4 - Growth of Functions.ppt
Lecture 4 - Growth of Functions.pptLecture 4 - Growth of Functions.ppt
Lecture 4 - Growth of Functions.ppt
 
Introduction to Artificial Neural Networks
Introduction to Artificial Neural NetworksIntroduction to Artificial Neural Networks
Introduction to Artificial Neural Networks
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
Recursive squaring
Recursive squaringRecursive squaring
Recursive squaring
 
Kotlinify Your Project!
Kotlinify Your Project!Kotlinify Your Project!
Kotlinify Your Project!
 
Ch01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluitonCh01 basic concepts_nosoluiton
Ch01 basic concepts_nosoluiton
 
F ch
F chF ch
F ch
 
컴퓨터 프로그램의 구조와 해석 1.2
컴퓨터  프로그램의 구조와 해석 1.2컴퓨터  프로그램의 구조와 해석 1.2
컴퓨터 프로그램의 구조와 해석 1.2
 
L25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptxL25-L26-Parameter passing techniques.pptx
L25-L26-Parameter passing techniques.pptx
 

More from James Wong

Multi threaded rtos
Multi threaded rtosMulti threaded rtos
Multi threaded rtos
James Wong
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
James Wong
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
James Wong
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
James Wong
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
James Wong
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
James Wong
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
James Wong
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
James Wong
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
James Wong
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
James Wong
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
James Wong
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
James Wong
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
James Wong
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
James Wong
 

More from James Wong (20)

Data race
Data raceData race
Data race
 
Multi threaded rtos
Multi threaded rtosMulti threaded rtos
Multi threaded rtos
 
Business analytics and data mining
Business analytics and data miningBusiness analytics and data mining
Business analytics and data mining
 
Data mining and knowledge discovery
Data mining and knowledge discoveryData mining and knowledge discovery
Data mining and knowledge discovery
 
Cache recap
Cache recapCache recap
Cache recap
 
Big picture of data mining
Big picture of data miningBig picture of data mining
Big picture of data mining
 
How analysis services caching works
How analysis services caching worksHow analysis services caching works
How analysis services caching works
 
Optimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessorsOptimizing shared caches in chip multiprocessors
Optimizing shared caches in chip multiprocessors
 
Directory based cache coherence
Directory based cache coherenceDirectory based cache coherence
Directory based cache coherence
 
Abstract data types
Abstract data typesAbstract data types
Abstract data types
 
Abstraction file
Abstraction fileAbstraction file
Abstraction file
 
Hardware managed cache
Hardware managed cacheHardware managed cache
Hardware managed cache
 
Object model
Object modelObject model
Object model
 
Abstract class
Abstract classAbstract class
Abstract class
 
Object oriented analysis
Object oriented analysisObject oriented analysis
Object oriented analysis
 
Concurrency with java
Concurrency with javaConcurrency with java
Concurrency with java
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Cobol, lisp, and python
Cobol, lisp, and pythonCobol, lisp, and python
Cobol, lisp, and python
 
Inheritance
InheritanceInheritance
Inheritance
 
Api crash
Api crashApi crash
Api crash
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Recently uploaded (20)

TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

Recursion

  • 2. Functions – reminder A function can call other functions. Return causes the execution of the function to terminate and returns a value to the calling function. The type of the value returned must be the same as the return-type defined for the function. return-type name(argType1 arg1, argType2 arg2, …) { function body; return value; }
  • 3. A recursive definition C functions can also call themselves!  However, usually not with the same parameters (why?) Some functions can be defined using smaller occurrences of themselves. Such a definition is called a “recursive definition” of a function.
  • 4. Recursive calling Example: void func(int n){ putchar(`*`); func(n); } Infinite series of * What is the problem ? Look for other problem …
  • 5. Factorial By definition : n! = 1*2*3*… *(n-1)*n Thus, we can also define factorial the following way:  0! = 1  n! = n*(n-1)! for n>0 (n-1)! *n
  • 6. Example - factorial int factRec(int n){ if (n==0 || n==1) return 1; return n*factRec(n-1); } int factorial(int n){ int fact = 1; while (n >= 1) { fact *=n; n--; } return fact; }
  • 7. Conclusions for Recursive calling Every recursive function has a “boundary condition”. The function stops calling itself when it is satisfied.
  • 8. Recursive factorial – step by step int factRec(int n) { if (n==0 || n==1) return 1; return n*factRec(n-1); } FactRec(4) n 4 Returns…
  • 9. Recursive factorial – step by step int factRec(int n) { if (n==0 || n==1) return 1; return n*factRec(n-1); } FactRec(4) n 4 Returns… 4*…
  • 10. Recursive factorial – step by step int factRec(int n) { if (n==0 || n==1) return 1; return n*factRec(n-1); } FactRec(4) n 4 Returns… FactRec(3) n 3 Returns…
  • 11. Recursive factorial – step by step int factRec(int n) { if (n==0 || n==1) return 1; return n*factRec(n-1); } FactRec(4) n 4 Returns… FactRec(3) n 3 Returns…
  • 12. Recursive factorial – step by step int factRec(int n) { if (n==0 || n==1) return 1; return n*factRec(n-1); } FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… 3*…
  • 13. Recursive factorial – step by step int factRec(int n) { if (n==0 || n==1) return 1; return n*factRec(n-1); } FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns…
  • 14. Recursive factorial – step by step int factRec(int n) { if (n==0 || n==1) return 1; return n*factRec(n-1); } FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns…
  • 15. Recursive factorial – step by step int factRec(int n) { if (n==0 || n==1) return 1; return n*factRec(n-1); } FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns… 2*…
  • 16. Recursive factorial – step by step int factRec(int n) { if (n==0 || n==1) return 1; return n*factRec(n-1); } FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns… FactRec(1) n 1 Returns…
  • 17. Recursive factorial – step by step int factRec(int n) { if (n==0 || n==1) return 1; return n*factRec(n-1); } FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns… FactRec(1) n 1 Returns…
  • 18. Recursive factorial – step by step int factRec(int n) { if (n==0 || n==1) return 1; return n*factRec(n-1); } FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns… FactRec(1) n 1 Returns… 1
  • 19. Recursive factorial – step by step int factRec(int n) { if (n==0 || n==1) return 1; return n*factRec(n-1); } FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… FactRec(2) n 2 Returns… 2*1
  • 20. Recursive factorial – step by step int factRec(int n) { if (n==0 || n==1) return 1; return n*factRec(n-1); } FactRec(4) n 4 Returns… FactRec(3) n 3 Returns… 3*2
  • 21. Recursive factorial – step by step int factRec(int n) { if (n==0 || n==1) return 1; return n*factRec(n-1); } FactRec(4) n 4 Returns… 4*6
  • 22. 1 #include <stdio.h> void print1(int n){ if (n>=0){ printf("%d ",n); print1(n-1); { { void main(){ int i = 3; print1(i); putchar('n'); { 3 2 1 0
  • 23. 2 #include <stdio.h> void print2(int n){ if (n>=0){ print2(n-1); printf("%d ",n); { { void main(){ int i = 3; print2(i); putchar('n'); { 0 1 2 3
  • 24. 3 #include <stdio.h> void print3(int n){ if (n>=0){ printf("%d ",n); print3(n-1); printf("%d ",n); { { void main(){ int i = 3; print3(i); putchar('n'); { 3 2 1 0 0 1 2 3
  • 25. 4 #include <stdio.h> void print4(int n){ if (n>=0){ print4(n-1); printf("%d ",n); print4(n-1); { { void main(){ int i = 3; print4(i); putchar('n'); { 0 1 0 2 0 1 0 3 0 1 0 2 0 1 0
  • 26. Another example - power  X y = x*x*…*x  Recursive definitions (assume non-negative y):  Base: x0 =1 1. X y = X*(X y-1 ) 2. X y =(X y/2 ) 2 (for even y’s only) y times
  • 27. Fibonacci Series Fibonacci definition:  n0 = 0  n1 = 1  nn = nn-1 + nn-2 0 1 1 2 3 5 8 13 21 34 55 …
  • 28. Fibonacci Iterative void fibonacci(int n) { int Fn, Fn1, Fn2, ind; Fn2 = 0 ; Fn1 = 1 ; Fn = 0 ; if ( n == 1 ) Fn = 1 ; for (ind=2 ; ind <= n ; ind++){ Fn = Fn1 + Fn2; Fn2 = Fn1; Fn1 = Fn; } printf("F(%d) = %d n", n, Fn); }
  • 29. Fibonacci Recursive fibonacci(1) fibonacci(5) fibonacci(4) fibonacci(3) fibonacci(3) fibonacci(2) fibonacci(2) fibonacci(1) fibonacci(2) fibonacci(1) fibonacci(1) fibonacci(0) fibonacci(0) fibonacci(1) fibonacci(0) int fibonacci(int n) { if (n==0) return 0; if (n==1) return 1; return fibonacci(n-1) + fibonacci(n-2); }
  • 30. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5
  • 31. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5
  • 32. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5
  • 33. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5
  • 34. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… 2*… y 5
  • 35. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… y 4
  • 36. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… y 4
  • 37. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… y 4
  • 38. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(…) y 4
  • 39. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(…) y 4 rec_pow(2, 2) x 2 Returns… y 2
  • 40. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(…) y 4 rec_pow(2, 2) x 2 Returns… y 2
  • 41. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(…) y 4 rec_pow(2, 2) x 2 Returns… y 2
  • 42. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(…) y 4 rec_pow(2, 2) x 2 Returns… square(…) y 2
  • 43. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(…) y 4 rec_pow(2, 2) x 2 Returns… square(…) y 2 rec_pow(2, 1) x 2 Returns… y 1
  • 44. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(…) y 4 rec_pow(2, 2) x 2 Returns… square(…) y 2 rec_pow(2, 1) x 2 Returns… y 1
  • 45. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(…) y 4 rec_pow(2, 2) x 2 Returns… square(…) y 2 rec_pow(2, 1) x 2 Returns… y 1
  • 46. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(…) y 4 rec_pow(2, 2) x 2 Returns… square(…) y 2 rec_pow(2, 1) x 2 Returns… y 1
  • 47. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(…) y 4 rec_pow(2, 2) x 2 Returns… square(…) y 2 rec_pow(2, 1) x 2 Returns… 2*… y 1
  • 48. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(…) y 4 rec_pow(2, 2) x 2 Returns… square(…) y 2 rec_pow(2, 1) x 2 Returns… 2*… y 1 rec_pow(2, 0) x 2 Returns… y 0
  • 49. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(…) y 4 rec_pow(2, 2) x 2 Returns… square(…) y 2 rec_pow(2, 1) x 2 Returns… 2*… y 1 rec_pow(2, 0) x 2 Returns… y 0
  • 50. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(…) y 4 rec_pow(2, 2) x 2 Returns… square(…) y 2 rec_pow(2, 1) x 2 Returns… 2*… y 1 rec_pow(2, 0) x 2 Returns… 1 y 0
  • 51. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(…) y 4 rec_pow(2, 2) x 2 Returns… square(…) y 2 rec_pow(2, 1) x 2 Returns… 2*1 y 1
  • 52. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(…) y 4 rec_pow(2, 2) x 2 Returns… square(2) y 2
  • 53. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… y 5 rec_pow(2, 4) x 2 Returns… square(4) y 4
  • 54. rec_pow – step by step int rec_pow(int x, int y) { if (y == 0) return 1; if (y%2 == 0) return square(rec_pow(x,y/2)); else return x*rec_pow(x,y-1); } rec_pow(2, 5) x 2 Returns… 2*16 y 5
  • 55. Exercise Write a program that receives two non-negative integers and computes their product recursively. Not * multiple operator !! Hint: Notice that the product a*b is actually a+a+… +a (b times).
  • 56. Solution int recMult( int x, int y ) { if( x == 0) return 0; return y + recMult( x-1,y); {
  • 57. Exercise Given the following iterative version of sum-of-digits calculation Find the recursive definition of this function (don’t forget the base case!) int sum_digits(int n){ int sum = 0; while (n > 0) { sum += n%10; n = n/10; } return sum; }
  • 58. Solution int sumOfDigits( int x ) { if( x < 0) x *= -1; if( x == 0 ) return 0; else return x % 10 + sumOfDigits( x / 10 ); }
  • 59. More uses Recursion is a general approach to programming functions. Its uses are not confined to calculating mathematical expressions! For example : write a function that finds the max member in an array of integer.
  • 60. Solution int rec_max(int arr[ ], int size){ int rest; if (size == 1) return arr[0]; else { rest = rec_max(arr+1, size-1); if (arr[0] > rest) return arr[0]; else return rest; } }
  • 61. int BinarySearch(int arr[],int x, int left, int right) { int middle; if(left>right) return -1; else { middle=(left+right)/2); if(arr[middle]==x) return middle; else if(x < arr[middle]) return BinarySearch(arr,x,left,middle-1); else return BinarySearch(arr,x,middle+1,right); } }
  • 62. Towers of Hanoi The Towers of Hanoi problem consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another rod, obeying the following rules:  Only one disk may be moved at a time.  Each move consists of taking the upper disk from one of the rods and sliding it onto another rod, on top of the other disks that may already be present on that rod.  No disk may be placed on top of a smaller disk.
  • 64. Recursive Solution To move n disks from peg A to peg C:  move n−1 disks from A to B. This leaves disk #n alone on peg A  move disk #n from A to C  move n−1 disks from B to C so they sit on disk #n
  • 65. Recursive Solution - Function void hanoi(int x, char from, char to, char aux){ if(x==1){ printf("Move Disk From %c to %cn", from, to); } else { hanoi(x-1,from,aux,to); printf("Move Disk From %c to %cn", from, to); hanoi(x-1,aux,to,from); } }
  • 66. Scope of variables - reminder A variable declared within a function is unrelated to variables declared elsewhere. A function cannot access variables that are declared in other functions.