[Legacy Content] This page contains very old information, which might not be valid anymore, they are only kept here for legacy purposes.
if you have any inquiries, feel free to contact me! Click here

Recursion

Created: Monday, 12 August 2013 Written by Ehab Eldeeb

Tracing and Writing Recursive Functions

 

How to trace a recursive function?

long exam (int n){  
    if (n == 0)
        return 1;
    else  
        return (10 * exam(n-1));
}


Returned Value at n = 4:
10000


Why?

at n = 4 --> 10 * exam(3)
           10 * exam(2)
              10 * exam(1)
                 10 * exam(0)
                    1

It goes like that .. edrab men ta7t le foo2 .. 1 * 10 * 10 * 10 * 10

 

How to write a Recursive Function?

The keyword in recursion is "inverting your idea"
Meaning that if the function multiplies 1 x 2 x 3 .. you will write it so that it multiplates 3 x 2 x 1
or in better words, let's say that you will be "decrementing your values"

Factorial function for example:

long factorial (int n){
int result = 1;
for(int i = 1; i <= n; i++)
result *= i;
return result;
}

See the for loop? it's an incrementing loop from 1 till n

Well, it's different with recursion, you will start from n and end with 1

long factorial (int n){
if (n == 0)
return 0; // Factorial 0 is 0
else if (n == 1)
return 1; // Factorial 1 is 1
else
return ( n * factorial(n-1)); // see that n-1? we are calling the function with a decremented value
}

 

And that's all about recursion :-)