Recursion

Maher Ben Dada
3 min readNov 3, 2021

I- Introduction:

There are two methods of algorithmic problem solving, the first one is called iteration and the second named recursion
What is the definition of recursion?
What is the difference between iteration and recursion?
What is the benefits of recursion?
What are the steps to write recursion function?

II- Definition:

Recursion is an algorithmic method which consists of call a subroutine in its own body. This method allows you to solve problems where you have to iterate a number of times depending on the number of data. A recursive subroutine is a module that “calls” itself. For each call, a value other than one is stored same formal parameter.

III- Difference between iteration and recursion:

The Recursion and Iteration both repeatedly execute the set of instructions. Recursion is when a statement in a function calls itself repeatedly.The iteration is when a loop repeatedly executes until the controlling condition becomes false.The primary difference between recursion and iteration is that recursion is a process, always applied to a function and iteration is applied to the set of instructions which we want to get repeatedly executed.

IV- Benefits of recursion:

Recursion has many advantages, some of which are:

  • For a recursive function, you only need to define the base case and recursive case, so the code is simpler and shorter than an iterative code.
  • Some problems are inherently recursive, such as Graph and Tree Traversal.

IV- Steps of recursion:

Here I will write a function that calculate the power of two given number, to do this task I will following this steps:

  • Define the return type and function name: float _pow_recursion
  • Define the function parameter: In this function I will use two variable x and y as float, in order to get result of x^y.
  • Define the specific case (s): Mean the case in which the function will stopped, this function has one specific case :

When y = 0, the function will return 1 because x^0 = 1.

  • Define the changing in parameter: In this function the re-call must change the value of variable y mean subtract 1 from the value of y until coming to zero.
  • This chart help us to untrestand how the function works

=> This is the function written with recursion algorithm:

float _pow_recursion(float x, float y)
{
if (y == 0)
return (1);
if (y < 0)
return (_pow_recursion(x, y + 1) / x);
return (_pow_recursion(x, y - 1) * x);
}

V- Conclusion:

The recursive solution includes:

* A recursive call by changing the value of the parameter.

* A condition for stopping the recursive call.

--

--