0

i have written a code for a fibonacci series returning the sum of the complete series, can the local "static int" variable be returned to the main function where the code is trying to print the sum.

Below is my code

#include<stdio.h>


int fiborecur(int n)
{
    static int first=0,second=1,sum=0,total=0;
    if( n>0 )
    {
        sum = first + second;
        total = total + sum;
        printf("  %d", sum);
        first = second;
        second = sum;
        fiborecur(n-1);
    }
    else
    {
        return total+1;
    }
}
int main()
{
    int n;
    printf("Enter the series length you want = ");
    scanf("%d", &n);
    printf("0  1");
    printf("\nSum of the series after return = %d\n", fiborecur(n-2));
    return 0;
}
2
  • 2
    you are not returning a static int, you are returning its value, so yes. but this looks like it will fail on a second invocation, since nothing resets the statics Commented Mar 14, 2015 at 4:29
  • you can return without recursive function it will work fine.. Do you need with recursive function? Commented Mar 14, 2015 at 5:43

2 Answers 2

2

Why are your int values declared as static? Use your return value to return the current total, and then it will happen automatically.

Static values plus recursion is a recipe for disaster.

Sign up to request clarification or add additional context in comments.

Comments

-1

Your problem is that you only return the total if n == 0, but your main function actually calls it with n > 0. Make your function always return total + 1, not only when n is zero (in other words just remove the else), and it should work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.