Q-07: Write a C/C++ program to display Fibanocci Series:
(i) Using Recursion
(ii) Using Iteration
  

Recursion Using - C


#include<stdio.h> int fibonacci(int n); void main() { int n, i; printf("Enter the number of terms: "); scanf("%d",&n); printf("\nFIBONACCI SERIES: \n"); for(i=0; i < n; i++) { printf("%d ",fibonacci(i)); } } int fibonacci(int n) { if(n==0) return 0; else if(n==1) return 1; else return (fibonacci(n-1)+fibonacci(n-2)); }

OUTPUT

Enter the number of terms:  7

FIBONACCI SERIES:
0     1     1     2     3     5     8
  

Iteration Using - C


#include<stdio.h> void fibonacci(int n); void main() { int n; printf("Enter the number of terms: "); scanf("%d",&n); fibonacci(n); } void fibonacci(int n) { int num1=0, num2=1, num3, i; if(n==0 || n==1) printf("%d ",num1); else { printf("%d %d ",num1,num2); for(i=2; i < n; i++) { num3 = num1 + num2; printf("%d ",num3); num1 = num2; num2 = num3; } } }

OUTPUT

Enter the number of terms:  6

FIBONACCI SERIES:
0     1     1     2     3     5
        

Rescursion Using - C++


#include<iostream> using namespace std; int fibonacci(int n); int main() { int n; cout<< "Enter the number of terms: "; cin>> n; cout<< "\nFIBONACCI SERIES: "<< endl; for(int i=0; i < n; i++) { cout<< fibonacci(i)<< " "; } } int fibonacci(int n) { if(n==0) return 0; else if(n==1) return 1; else return (fibonacci(n-1)+fibonacci(n-2)); }

OUTPUT

Enter the number of terms:  10

FIBONACCI SERIES:
0     1     1     2     3     5     8     13     21     34
  

Iteration Using - C++


#include<iostream> using namespace std; void fibonacci(int n); int main() { int n; cout<< "Enter the number of terms: "; cin>> n; cout<< "\nFIBONACCI SERIES:"<< endl; fibonacci(n); return 0; } void fibonacci(int n) { int num1=0, num2=1, num3; if(n==0 || n==1) cout<< num1<< " "; else { cout<< num1<< " "<< num2<< " "; for(int i=2; i < n; i++){ num3 = num1 + num2; cout<< num3<<" "; num1 = num2; num2 = num3; } } }

OUTPUT

Enter the number of terms:  1

FIBONACCI SERIES:
0