Write a program to find nth Fibonacci term

Write a program to find nth Fibonacci term
Used function

  1. #include<stdio.h> 
  2.   
  3. int fibo(int num) 
  4. {
  5.   int fibonacci[num+2];
  6.   int i; 
  7.   
  8.   fibonacci[0] = 0; 
  9.   fibonacci[1] = 1; 
  10.   
  11.   for (i = 2; i <= num; i++) { 
  12.       fibonacci[i] = fibonacci[i-1] + fibonacci[i-2]; 
  13.   } 
  14.   
  15.   return fibonacci[num]; 
  16.   
  17. int main() { 
  18.     int num; 
  19.     printf("Enter the number to find nth fiboacci term : ");
  20.     scanf("%d", &num);

  21.     int first=0, second=1, third;
  22.     printf("%4d%4d", first, second);
  23.     for(int i=3; i <= num; i++) {
  24.         third=first+second;
  25.         first=second;
  26.         second=third;
  27.         printf("%4d", third);
  28.     }

  29.     printf("\n\n%dᵗʰ fibonacci term is : %d", num, fibo(num));
  30.     return 0; 
  31. }

Recursion

  1. #include <stdio.h>

  2. int fibo(int num);

  3. int main()
  4. {
  5.     int num;
  6.     int fibonacci;
  7.   
  8.     printf("Enter the number to find nth fiboacci term : ");
  9.     scanf("%d", &num);
  10.    
  11.     int first=0, second=1, third;
  12.     printf("%4d%4d", first, second);
  13.     for(int i=3; i <= num; i++) {
  14.         third=first+second;
  15.         first=second;
  16.         second=third;
  17.         printf("%4d", third);
  18. }

  19.     if(num < 0) {
  20.         printf("Fibonacci of negative number is not possible.\n");
  21.     }
  22.     else {
  23.         fibonacci = fibo(num);
  24.         printf("The %dᵗʰ fibonacci term is : %d\n", num, fibonacci);
  25.     }
  26.    /* //or (this one is also correct) 
  27.     fibonacci = fibo(num); 
  28.     printf("%dᵗʰ fibonacci term is : %d", num, fibonacci);
  29.     */
  30.     return 0;
  31. }

  32. int fibo(int num) 
  33. {
  34.     if(num == 0)
  35.         return 0;
  36.     else if(num == 1)
  37.         return 1;
  38.     else 
  39.         return fibo(num-1) + fibo(num-2); 
  40. }

একটি মন্তব্য পোস্ট করুন