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

09 - C Basics – Recursion, Calling by Value _ Calling by Reference

The document covers the basics of recursion in programming, explaining how recursive functions work, particularly through the example of calculating factorials. It also discusses the concepts of passing arguments by value and by reference, including how to implement a swap function and return multiple values using reference parameters. The importance of having a base case in recursion to prevent infinite loops and stack overflow is emphasized.

Uploaded by

rosahshhsh
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)
0 views

09 - C Basics – Recursion, Calling by Value _ Calling by Reference

The document covers the basics of recursion in programming, explaining how recursive functions work, particularly through the example of calculating factorials. It also discusses the concepts of passing arguments by value and by reference, including how to implement a swap function and return multiple values using reference parameters. The importance of having a base case in recursion to prevent infinite loops and stack overflow is emphasized.

Uploaded by

rosahshhsh
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/ 20

C Basics

09 - Recursion, calling by value & calling by reference


/AhmedHatemS

/c/AhmedHatemS
What is the content?
➢Recursion (Recursive Functions)
❑Factorial.
➢Passing Arguments
❑Call / Pass by Value.
❑Call / Pass by Reference.
❑Returning multiple values.
Recursion
Recursion is a programming concept whereby a function invokes
itself.

Input Output

Recursion is typically used to solve problems that are decomposable


into sub-problems that are just like the original problem, but a step
closer to being solved.
Recursion without a Base Case
Here’s a recursive function called foo.
What happens when this function is called?

void foo( string str )


{
Printf(“%s”,str);
foo( str );
}
foo will print a string and call itself, which will
print another string and call itself again, which will
print another string and call itself yet again .. and
on and on infinitely.

However, every time a function is called, some


space is set aside in the stack called
a frame and every function call results in a new
frame being created.
Recursion without a Base Case
So, if foo calls itself infinitely, we’ll eventually run
out of stack memory and try to access memory

void foo( string str )


{
Printf(“%s”,str);
foo( str );
}
that doesn’t belong to us, in which case our
program will fail with a segmentation fault.

To avoid this situation, we need to make sure


there’s always a way to break out of recursive
calls -- we’ll call this the base case. When the
base condition is met, the function should return
without making a recursive call. Let’s make sure
we have a base case in the next example :)
Factorial
For our next example, let’s think about the factorial
operation. The factorial operation is a perfect candidate for
recursion because it is a problem that can easily be broken
up into similar smaller problems!

n! = n * (n - 1) * (n - 2) * … * 1
5! = 5 * 4 * 3 * 2 * 1
So if we want to calculate the factorial of 5, we can think of
it as multiplying 5 by the factorial of 4:
5! = 5 * 4!
Similarly, to calculate the factorial of 4, we multiply 4 by the
factorial of 3:
4! = 4 * 3!
And so on ..
Let’s implement a factorial function in C!
This recursive function calculates the factorial of its integer
argument, and unlike the last function we saw, this one has a base
case!

Think through what happens when you pass this function an


argument of 3:
unsigned int factorial(unsigned int n) {
if (n <= 1)
{
return 1;
}
else
{
return n * factorial(n - 1);
}
}

• factorial(3) returns 3 * factorial(2)


• factorial(2) returns 2 * factorial(1)
Once the base case is reached, all of the factorial()calls
will return in succession to give us an answer of 6.

factorial(3) = 3 * factorial(2)

2 * factorial(1)

Let’s see what’s going on in the stack as this recursive


function executes!
Let’s zoom in on the stack as this function executes:
• main() calls factorial(3)
heap

factorial ( 3 )

stack main ( )

Every function call results in a new frame being created. These frames are
arranged on top of each other in the stack, with the frame for the most recently
called function (the active frame) at the top.
• main() calls factorial(3)
• factorial(3) calls factorial(2)

heap

factorial ( 2 )
factorial ( 3 )

stack main ( )

factorial(2) is now the active frame.


• main() calls factorial(3)
• factorial(3) calls factorial(2)
• factorial(2) calls factorial(1)

heap

factorial ( 1 )
factorial ( 2 )
factorial ( 3 )

stack main ( )

factorial(1) is now the active frame.


• main() calls factorial(3)
• factorial(3) calls factorial(2)
• factorial(2) calls factorial(1)

heap

factorial(1)returns 1
to factorial(2). Its
frame is destroyed, and the
one for the function below
(in this case
1 factorial(2)) becomes
active again.
factorial ( 2 )
factorial ( 3 )

stack main ( )

• factorial(1) returns 1 to factorial(2)


• main() calls factorial(3)
• factorial(3) calls factorial(2)
• factorial(2) calls factorial(1)

heap

factorial(2)returns 2
to factorial(2). Its
frame is destroyed, and the
one for the function below
(in this case
factorial(3)) becomes
active again.
2
factorial ( 3 )

stack main ( )

• factorial(1) returns 1 to factorial(2)


• factorial(2) multiplies 1 * 2 and returns 2 to factorial(3)
• main() calls factorial(3)
• factorial(3) calls factorial(2)
• factorial(2) calls factorial(1)

heap

factorial(3)returns 6
to main(). Its frame is
destroyed, and the one for
the function below (in this
case main()) becomes
active again.

Nice! Our function


calculated the correct
6 answer!
3! = 3 * 2 * 1 = 6
stack main ( )

• factorial(1) returns 1 to factorial(2)


• factorial(2) multiplies 1 * 2 and returns 2 to factorial(3)
• factorial(3) multiplies 2 * 3 and returns 6 to main()
Pass-by-value versus Pass-by-reference
• So far we’ve been passing everything by value –
makes a copy of the variable; changes to the
variable within the function don’t occur outside
the function.
For example: What should be the output?
Pass-by-value versus Pass-by-reference
• If you w ant to modify the original variable as
o p p o s e d t o m a k i n g a c o p y, p a s s t h e v a r i a b l e b y
reference (int &a instead of int a).

For example: What should be the output?


Implementing a Swap Function

void swap( int &a, int &b )


{
int temp = a;
a = b;
b = temp;
}

int main()
{
int q = 3;
int r = 5;
swap( q, r );
Printf("q %d”, q) ; // q 5
Printf(“r %d”, r ); // r 3
}
Returning Multiple Values
• The return statement only allow s you to return 1
value. Passing output variables by reference
overcomes this limitation.

i n t d i v i d e ( i n t n u m e r a t o r, i n t d e n o m i n a t o r, i n t & r e m a i n d e r ) {
remainder = numerator % denominator;
return numerator / denominator;
}
int main() {
int num = 14;
int den = 4;
int rem;
int result = divide( num, den, rem ); // 3 * 4 + 2 = 14
Printf("%d * %d + %d = % d ", result, den, rem, num);
}
Next

You might also like