Wednesday, July 18, 2018

Implement functions to print nth Fibonacci number using iteration and recursive method. Compare the performance of two methods by counting number of steps executed on various inputs. Also draw a comparative chart. (Fibonacci series 1, 1, 2, 3, 5, 8…..  Here 8 is the 6th Fibonacci number) - DAA

#include <stdio.h>

int i, n, t1 = 1, t2 = 1, temp, d=1;
int count1=0, count2=0;
int main()
{
    printf("Enter the number: ");
    scanf("%d", &n);

    printf("Fibonacci Series: ");
    iteration(n); 
    printf("\nFibonacci Series Rec: ");
    for(i=1;i<=n;i++)
    {
     printf("%d, ",rec(d));
 d++;
    }
    printf("\nIteration Count: %d",count1);
    printf("\nRec Count: %d",count2);
}

int iteration(int n)
{
    count1=count1+3;
    for(i=1;i<=n;i++)
    {
 count1=count1+4;
        printf("%d, ", t1);
        temp = t1 + t2;
        t1 = t2;
        t2 = temp;
    }
    count1=count1+2;
    return 0;

}

int rec(int n)
{ 
 if(n<=1)
 {
  count2=count2+2;
  return n;
 }
 else
 {
  count2=count2+2;
  return rec(n-1)+rec(n-2);
 }
}

No comments:

Post a Comment