Recursive Function in Program
Recursive Function is a function that calls itself. A function a1() is also recursive if it calls a function a2(), which under some circumstances calls a1(), creating a cycle in the sequence of calls. This kind of ability to invoke itself allowing a recursive function to be repeated with any different parameter values. Mostly, recursive function is less efficient than iteration (looping) due to the overhead for the extra function calls. However, by using recursion method allowing us to specify a very natural, simple solution to a problem that would be very difficult to solve if using another method. so that’s why recursion is a powerfull method in problem solving and programming.
Using Recursive Function for Problem Solving
Problems that need a recursive solution mostly have the following characterstics :
- One or More simple problem (a problem that can be solved using simple method) have a straight forward, non recursive solution.
- The problem can be redefined into a simple problem that can be solved easily.
- By applying this redefinition process every time recursive function called, the problem eventually reduced entirely to a simple cases.
You can see the recursive algorithm that we will use generally from example below
1234 If problemvar = simple case can be solvedsolve itelseredefine problemvar using recursion
That example illustrate how recursion works generally. Mostly recursive method used when you want to splitting a problem into a simpler problem.
Another example of recursion, let’s consider how we will solve the problem of multiplying 12 by 2, assuming we only know addition tables not multiplication tables. Because we assume don’t know multiplication tables. Multiplying 12 by 2 straight forward can’t be solved. So we will split the problem into many problems we can solve. In this case, by using C programming language.
123456789 int multiply(int a, int b){int output;if (b == 1)output = a;elseoutput = a + multiply (a, b-1); /* Recursive step by calling it's own function*/return (output);}
From example above we splitting the original problem into two simpler problems. The first problem solved by calling multiply function again (multiply (a, b-1)). After that we check if the new second problem is greater than 1. The program will call multiply function again till b = 1.