Write a program to find nth Fibonacci term
Used function
Recursion
Used function
- #include<stdio.h>
- int fibo(int num)
- {
- int fibonacci[num+2];
- int i;
- fibonacci[0] = 0;
- fibonacci[1] = 1;
- for (i = 2; i <= num; i++) {
- fibonacci[i] = fibonacci[i-1] + fibonacci[i-2];
- }
- return fibonacci[num];
- }
- int main() {
- int num;
- printf("Enter the number to find nth fiboacci term : ");
- scanf("%d", &num);
- int first=0, second=1, third;
- printf("%4d%4d", first, second);
- for(int i=3; i <= num; i++) {
- third=first+second;
- first=second;
- second=third;
- printf("%4d", third);
- }
- printf("\n\n%dᵗʰ fibonacci term is : %d", num, fibo(num));
- return 0;
- }
Recursion
- #include <stdio.h>
- int fibo(int num);
- int main()
- {
- int num;
- int fibonacci;
- printf("Enter the number to find nth fiboacci term : ");
- scanf("%d", &num);
- int first=0, second=1, third;
- printf("%4d%4d", first, second);
- for(int i=3; i <= num; i++) {
- third=first+second;
- first=second;
- second=third;
- printf("%4d", third);
- }
- if(num < 0) {
- printf("Fibonacci of negative number is not possible.\n");
- }
- else {
- fibonacci = fibo(num);
- printf("The %dᵗʰ fibonacci term is : %d\n", num, fibonacci);
- }
- /* //or (this one is also correct)
- fibonacci = fibo(num);
- printf("%dᵗʰ fibonacci term is : %d", num, fibonacci);
- */
- return 0;
- }
- int fibo(int num)
- {
- if(num == 0)
- return 0;
- else if(num == 1)
- return 1;
- else
- return fibo(num-1) + fibo(num-2);
- }
একটি মন্তব্য পোস্ট করুন