DEV Community

Sakamuri Tharun
Sakamuri Tharun

Posted on

Recursion using functions

#c

Different Ways of Writing Recursive Functions
1)Function calling itself: (Direct way)
Most of us aware atleast two different ways of writing recursive programs. Given below is towers of Hanoi code. It is an example of direct calling.

include

// Assuming n-th disk is bottom disk (count down)

void tower(int n, char sourcePole, char destinationPole, char auxiliaryPole)
{

// Base case (termination condition)

if(0 == n)

 return;
Enter fullscreen mode Exit fullscreen mode

// Move first n-1 disks from source pole

// to auxiliary pole using destination as

// temporary pole

tower(n-1, sourcePole, auxiliaryPole,

  destinationPole);


// Move the remaining disk from source
Enter fullscreen mode Exit fullscreen mode

// pole to destination pole

printf("Move the disk %d from %c to %c\n",

n,sourcePole, destinationPole);
Enter fullscreen mode Exit fullscreen mode

// Move the n-1 disks from auxiliary (now source)

// pole to destination pole using source pole as

// temporary (auxiliary) pole

tower(n-1, auxiliaryPole, destinationPole,

 sourcePole);
Enter fullscreen mode Exit fullscreen mode

}
int main()
{

tower(3, 'S', 'D', 'A');

return 0;
}

2)Recursion using mutual function call: (Indirect way)
Indirect calling. Though least pratical, a function [funA()] can call another function [funB()] which inturn calls [funA()] former function. In this case both the functions should have the base case.
Defensive Programming:
We can combine defensive coding techniques with recursion for graceful functionality of application. Usually recursive programming is not allowed in safety critical applications, such as flight controls, health monitoring, etc. However, one can use a static count technique to avoid uncontrolled calls (NOT in safety critical systems, may be used in soft real time systems).

void recursive(int data)
{

static callDepth;

if(callDepth > MAX_DEPTH)

  return;
Enter fullscreen mode Exit fullscreen mode

// Increase call depth

callDepth++;

// do other processing

recursive(data);

// do other processing

// Decrease call depth

callDepth--;
}

callDepth depth depends on function stack frame size and maximum stack size.
Recursion using function pointers: (Indirect way)
Recursion can also implemented with function pointers. An example is signal handler in POSIX complaint systems. If the handler causes to trigger same event due to which the handler being called, the function will reenter.

Top comments (0)