Loading…
DAA · Dynamic programming · Program 10 · In the record
Write a program in c to find the fibonacci series using recursion and find its execution time using the time function.
Algorithm: Fib(n) 1. Start 2. If (n <= 1) then 3. Return n 4. Return Fib(n-1) + Fib(n-2) 5. Stop Algorithm: FibonacciSeries(n) 1. Start 2. For i <- 0 to (n-1) do 3. print Fib(i) 4. Stop
1#include<stdio.h>2#include<time.h>3 4int calls=0;5 6int fib(int n) {7 calls++;8 if(n<=1)9 return n;10 return fib(n-1)+fib(n-2);11}12 13int main() {14 int n,i;15 printf("Enter the number of terms:");16 scanf("%d",&n);17 18 clock_t start=clock();19 printf("\nFibonacci series:");20 for(i=0;i<n;i++)21 printf("\t%d",fib(i));22 clock_t end=clock();23 double time_taken=(double)(end-start)/CLOCKS_PER_SEC;24 25 printf("\nNumber of function calls:%d",calls);26 printf("\nTime taken:%f seconds",time_taken);27 printf("\nTime complexity: O(2^n)");28 printf("\nSpace complexity: O(n)");29 printf("\n");30 return 0;31}10Enter the number of terms:10 Fibonacci series: 0 1 1 2 3 5 8 13 21 34 Number of function calls:276 Time taken:0.000009 seconds Time complexity: O(2^n) Space complexity: O(n)
Run program 10 in your browser
C · clang → WebAssembly. Change the code or the input, run it, break it, and see what happens.