C program to find Fibonacci series

 

Hi friends, this lesson is going to show you how to write a C program to print Fibonacci series.

This is the example of Fibonacci series:
0, 1, 1, 2, 3, 5, 8..

Basically the Fibonacci series is finding the next number by adding the first two numbers, for example,

0,1 -> 0 +1 =1 ( 1 is the next number)
0,1,2 -> 1+1 = 2 (2 is the next number)
0,1,2 -> 1+2 = 3
0,1,2,3 -> 2+3 = 5
etc.,

When the length becomes longer, finding the next number will become harder if you do it manually, but you know we are programmers, we can make it very simple by writing a C program.

Here is the entire C program to find the Fibonacci series:

#include<stdio.h>

int main()
{
	int limit, first_num = 0, second_num = 1, next_num;
	
	//get the limit of fibonacci series	
	printf("Enter the limit: \n");
	scanf("%d",&limit);
	
	printf("Fibonacci series are \n", limit);
	
	//print first two numbers of fiboncacci series
	printf("%d \n", first_num); 
	printf("%d \n", second_num);
	
	/* here we are checking > 2 because 
	   we have already printed two numbers 
	   of fiboncacci series above
	*/
	//loop through the limit till it becomes 0 (zero)
	while(limit > 2)
	{	   
	   //add the first value and second to get the next value
	   next_num   = first_num + second_num;
	   
	   //assign second value to first
	   //next value to second
	   //to find the next series
	   first_num  = second_num;
	   second_num = next_num;
	   
	   //print the next value
	   printf("%d\n",next_num);
	   
	   //decrement the limit by one 
	   limit--;
	}
	
	return 0;
}

The above code is self explanatory, just read the comments in it to understand.

When you run this program it will ask you to enter the limit of Fibonacci series that you want to see, for instance if you type 10, so it will generate 10 series of Fibonacci numbers.

This kind of programs often asked in Interviews, so prepare yourselves. Good luck!  Thanks!

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top