Search code examples
crecursioncallstack-overflowtail-recursion

Stack limit exceeded due to repeated recursion


This code is to print the Fibonacci series using recursion. So I thought to devise a recursion instead of using iteration but as soon as I just execute the code and as soon as the value provider function is executed it is showing some error "segmentation error". I want to do it this way only... Can anyone help? I'm just a beginner so please help and encourage me...

#include<stdio.h>

int fibonacci(int n)
{
    int res;
    if(n==0)
        return 0;
    if(n==1)
        return 1;
    else
        res = fibonacci(n-1)+fibonacci(n-2);
    return res;

}
int value_provider(int n)
{
    int choice1;
    if(n>=0)
    {
        choice1 = fibonacci(n-1);
        n -- ;
    }
    printf("%d",choice1);
    if(n>=0)
    {
        value_provider(n);
    }

}

void main()
{
    int n;
    printf("enter the number");
    scanf("%d",&n);
    value_provider(n);
}

This code is showing segmentation fault... What can I do to remove it rather than changing the code? I want to do it only this way; please help!


Solution

  • I think your value_provider function has poor terminating conditions.

    • Don't try to calculate fibonacci of -1 so n must be >=1

    • Also once n is zero you need to finish the recursion, don't call value_provider again.

    Try something more like this;

    int value_provider(int n)
    {
      int choice1=-1;
      if(n>=1)
      {
         choice1 = fibonacci(n-1);
         n -- ;
      }
      printf("%d ",choice1);
      if(n>0)
      {
        value_provider(n);
      }
    }