beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

C Program to display Fibonacci series

By Chaitanya Singh | Filed Under: C Programs

In this tutorial, we will learn two following ways to display Fibonacci series in C programming language:
1) Using For loop
2) Using recursion

Fibonacci Series in C using loop

A simple for loop to display the series. Program prompts user for the number of terms and displays the series having the same number of terms.

#include<stdio.h>
int main()
{
    int count, first_term = 0, second_term = 1, next_term, i;
 
    //Ask user to input number of terms 
    printf("Enter the number of terms:\n");
    scanf("%d",&count);
 
    printf("First %d terms of Fibonacci series:\n",count);
    for ( i = 0 ; i < count ; i++ )
    {
       if ( i <= 1 )
          next_term = i;
       else
       {
          next_term = first_term + second_term;
          first_term = second_term;
          second_term = next_term;
       }
       printf("%d\n",next_term);
    }
 
    return 0;
}

Output:

Enter the number of terms: 8
First 8 terms of Fibonacci series:
0
1
1
2
3
5
8
13

Program to display Fibonacci series using recursion

Here we are using a user defined function fibonacci_series() that calls itself recursively, in order to display series for the entered number of terms.

#include<stdio.h>
int fibonacci_series(int);
int main()
{
   int count, c = 0, i;
   printf("Enter number of terms:");
   scanf("%d",&count);
 
   printf("\nFibonacci series:\n");
   for ( i = 1 ; i <= count ; i++ )
   {
      printf("%d\n", fibonacci_series(c));
      c++; 
   }
 
   return 0;
}
int fibonacci_series(int num)
{
   if ( num == 0 )
     return 0;
   else if ( num == 1 )
     return 1;
   else
     return ( fibonacci_series(num-1) + fibonacci_series(num-2) );
}

Output:

Enter number of terms: 6
Fibonacci series:
0
1
1
2
3
5

Enjoyed this post? Try these related posts

  1. C Program to Sort set of strings in alphabetical order
  2. C Program to Convert Decimal to Octal Number
  3. C Program to Swap two numbers
  4. C Program to Check whether an Alphabet is Vowel or Consonant
  5. C Program to arrange numbers in ascending order
  6. C Program to Print an Integer entered by a user

Leave a Reply Cancel reply

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

Programs

  • C Programs
  • Java Programs

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2019 BeginnersBook . Privacy Policy . Sitemap