09 - C Basics – Recursion, Calling by Value _ Calling by Reference
09 - C Basics – Recursion, Calling by Value _ Calling by Reference
/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
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!
factorial(3) = 3 * factorial(2)
2 * factorial(1)
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 ( )
heap
factorial ( 1 )
factorial ( 2 )
factorial ( 3 )
stack main ( )
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 ( )
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 ( )
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.
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