Fibonacci series is a series of numbers in which each number is the sum of preceding 2 numbers.Below is fibonacci series with 6 terms.
When a function invokes,its activation record is pushed on the call stack and when it finishes execution,its activation record is popped off from the call stack.Activation record comprises of many things but I am just showing the things that help understand recursion.Below I trace the fib().
0 1 1 2 3 5
Code
#include<stdio.h>
void fib(int);
int main()
{
int no;
printf("Enter no of terms ");
scanf("%d",&no);
printf("\n%d %d",0,1);
fib(no);
return 0;
}
void fib(int no)
{
static int a=0,b=1,c;
if(no>2)
{
c = a + b;
a = b;
b = c;
printf(" %d",c);
fib(no-1);
}
}
Note : A static variable retains its value within function calls.
Code Tracing
When a function invokes,its activation record is pushed on the call stack and when it finishes execution,its activation record is popped off from the call stack.Activation record comprises of many things but I am just showing the things that help understand recursion.Below I trace the fib().
No comments:
Post a Comment