bsc

Comprehensive codebase and cou...
Log | Files | Refs | Activity | README | LICENSE

root / semester_1 / assignment-secondary / assignment-s-17.c

assignment-s-17.c (1489B)


      1 /* Write a program to display the Fibonacci series
      2     (i) using recursion
      3     (ii) using iteration
      4 */
      5 
      6 #include <stdio.h>
      7 
      8 long long int fib_rec(int);
      9 long long int fib_tail_rec(int, long long int, long long int);
     10 void fib_rec_print(int);
     11 void fib_ite_print(int);
     12 
     13 int main()
     14 {
     15     int n;
     16     printf("Enter the number of terms: ");
     17     scanf("%d", &n);
     18     fib_rec_print(n);
     19     fib_ite_print(n);
     20     return 0;
     21 }
     22 
     23 long long int fib_rec(int n)
     24 {
     25     if (n == 0 || n == 1)
     26     {
     27         return n;
     28     }
     29     else
     30     {
     31         return fib_rec(n - 1) + fib_rec(n - 2);
     32     }
     33 }
     34 
     35 long long int fib_tail_rec(int n, long long int t1, long long int t2)
     36 {
     37     if (n == 0)
     38     {
     39         return t1;
     40     }
     41     else if (n == 1)
     42     {
     43         return t2;
     44     }
     45     else
     46     {
     47         return fib_tail_rec(n - 1, t2, t1 + t2);
     48     }
     49 }
     50 
     51 void fib_rec_print(int n)
     52 {
     53     int i;
     54     printf("\nFibonacci Series (Recursion):");
     55     for (i = 0; i < n; i++)
     56     {
     57         printf("  %lld", fib_rec(i));
     58     }
     59     printf("\nFibonacci Series (Tail-Recursion):");
     60     for (i = 0; i < n; i++)
     61     {
     62         printf("  %lld", fib_tail_rec(i, 0, 1));
     63     }
     64 }
     65 
     66 void fib_ite_print(int n)
     67 {
     68     int i;
     69     long long int t1 = 0, t2 = 1, temp;
     70     printf("\nFibonacci Series (Iteration):");
     71     if (n > 0)
     72     {
     73         printf("  0");
     74     }
     75     if (n > 1)
     76     {
     77         printf("  1");
     78     }
     79     for (i = 2; i < n; i++)
     80     {
     81         printf("  %lld", t1 + t2);
     82         temp = t1;
     83         t1 = t2;
     84         t2 = temp + t2;
     85     }
     86 }
© notamitgamer • Site Built: 2026-09-05 01:53:16 UTC • git-mirror commit: c170d72 [view raw info]
Originally created with stagit • modified by notamitgamer
Forked from github.com/notamitgamer/git-mirror