Home » Software » Recursive Function in Program

Recursive Function in Program

(追記) (追記ここまで)

recursive 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

1
2
3
4
If problemvar = simple case can be solved
solve it
else
redefine 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.

(追記) (追記ここまで)
Recursive-Method Recursive Function in Program

Using recursion to splitting a problem into smaller problems

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.

1
2
3
4
5
6
7
8
9
int multiply(int a, int b)
{
int output;
if (b == 1)
output = a;
else
output = 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.

February 18, 2014 Technology Tips Software No Comment

You May Want to See :

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website

This site uses Akismet to reduce spam. Learn how your comment data is processed.

AltStyle によって変換されたページ (->オリジナル) /