What is recursion in Programming

What is recursion in Programming


A function invoking itself is known as recursion. Recursion is an alternative to iteration. Recursion is very close to mathematical way of solving a given problem.

Advantages of recursion are, it is straight forward and easy. Disadvantage of recursion is, it occupies more memory on the stack when compared to iteration.

Note: Remember to write an exit condition while using recursion. If there is no exit condition, then the function will call itself infinitely.

Consider the following program which calculates the factorial of a number using recursion:

In the above program the exit condition is if(n==0 || n==1) return 1;

The recursive call is fact(n-1).

Note: In the above program there is no function declaration (prototype) for the function fact(). If the function definition is written before main(), there is no need of writing function declaration.

Passing an Array as a Parameter


Like we are able to pass variables, we can also pass arrays as arguments to a function. A function prototype which accepts an array and its size as parameters is as follows:
void PrintArray(int nums[ ], int size);

Consider the following program which contains a function that takes an array and its size as arguments and calculates the largest element in the array.


Note that in the above program there is no need to write square brackets in the function call largest(nums, 5).

Parameter Passing Techniques


In C++ we have three ways for passing arguments to a function. They are: pass-by-value, pass-by-reference, and pass-by-address.

Pass-by-value

Generally used way to pass arguments is pass-by-value. In this method, the arguments passed in the function call are copied to formal parameters in the function definition. So, any changes made to the formal parameters are not reflected on the actual parameters. Consider the following swap function which demonstrates pass-by-value:

Let’s assume that in the main() function we are writing the following code:
int a = 10, b = 20;
swap(a, b);

Although the values of x and y are being interchanged, since they are copies of a and b, the values of a and b remains the same i.e., 10 and 20 respectively.

No comments:

Post a Comment