Home » Blog » Fibonacci Series With Recursion And Without Recursion

Fibonacci Series With Recursion And Without Recursion

There are two ways to write the Fibonacci Series program:

  1. Fibonacci Series without recursion
  2. Fibonacci Series using recursion

Fibonacci Series Without Recursion

#include<stdio.h>   
#include<conio.h> 
void main()    
{    
	int n1=0,n2=1,n3,i,number; 
	clrscr(); 
	
	printf("Enter the number of elements:");    
	scanf("%d",&number);    
	printf("\n%d %d",n1,n2); //print 0 and 1
	
	for(i=2;i<number;++i) //loop starts from 2 because 0 and 1 are already printed    
	{    
		n3=n1+n2;    
		printf(" %d",n3);    
		n1=n2;    
		n2=n3;    
	}  
	getch(); 
}

OutPut

Enter the number of elements:15
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Fibonacci Series With Recursion

#include<stdio.h>
#include<conio.h>
 
void printFibonacci(int n){    
    static int n1=0,n2=1,n3;    
    if(n>0)
	{    
         n3 = n1 + n2;    
         n1 = n2;    
         n2 = n3;    
         printf("%d ",n3);    
         printFibonacci(n-1);    
    }    
}    
void main()
{    
	int n;  
	clrscr();
	
	printf("Enter the number of elements: ");    
	scanf("%d",&n);    
	
	printf("Fibonacci Series: ");    
	printf("%d %d ",0,1);    
	printFibonacci(n-2); //n-2 because 2 numbers are already printed    
	getch();
}

OutPut

Enter the number of elements:15
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

 

Leave a Reply

Your email address will not be published.