Printing Fibonacci Series in C

Fibonacci series is a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, etc.

C program for Fibonacci Series

#include<stdio.h> int main() {  int n, first = 0, second = 1, next, i;  printf("Enter the number of terms");  scanf("\%d", &n);  printf("\%d terms of Fibonacci series are :",n);  for ( i=0; i<n ;i++ )  {   if ( i <= 1 )       next = i; //first 2 terms   else   {       next = first + second;       first = second;       second = next;   } printf("\%d ",next);  } return 0; } 

Output

C program to print fibonacci series

Variable ‘first’, ‘second’ The first and second term of fibonacci is always ‘0’ and ‘1’

Variable ‘next’ contains sum of first and second variable i.e. the next element in the series

Explanation:

  • if(i<=1) checks if the number of terms required is 1 or 2 and prints directly, because the first two terms are already known and computation is not required
  • ‘next=first+second’ adds the 2 terms and stores it as a 3rd term in series
  • ‘first = second’ makes the second term as first
  • ‘Second = next’ makes the third term as second, for adding the new ‘first’ and ‘second’ to make next term ‘next’ available.
  • printf(“\%d”, next); Prints the new term we obtained

C program to print fibonacci series

Thank you for reading.

Tweet your queries and feedback to @PsychoCodes or leave a message on our Facebook page. You can also comment your questions below.

Also, don’t forget to subscribe to our Newsletter.

If you like this article, then please share it and help us grow.


Preorder and Postorder Traversal of binary tree in Python
02 September 2018

Binary Tree in Python
02 September 2018

Image Sharpening by High Pass Filter using Python and OpenCV
17 August 2018

Explaining Register variables in C with examples
17 August 2018

C program to generate all combinations of N-Bit Binary String
10 July 2018

Data Autosave System using PHP, MySQL and AJAX
06 July 2018

Понравилась статья? Поделиться с друзьями:
Добавить комментарий