Adsense 728 * 15

Search

Custom Search

Program to Print Fibonacci Series in C, C++

Write a program to print fibonacci series in C, C++. 

What is Fibonacci series ?



In fibonacci series the first two numbers are 0 and 1 , and the remaining numbers are the sum of previous two numbers.


For example- 0  1  1  2  3  5  8  13 ............


So first 0 and 1 is printed, next 1 is the sum of 0 + 1,  similarly 2 is the sum of 1 + 1 and so on.


Interview Questions For Practice.

Print Fibonacci Series using Recursion.

C++ Program to Generate First Ten Numbers of Fibonacci Series



 
#include<iostream>
using namespace std;

int main( )
{
   int n, i, first = 0, second = 1, third;
   
   /* Print first two numbers 0 and 1 .*/

   cout << first  << endl;
   cout<<second << endl;

   /* Loop from 2 to 10. */

   for (i = 2 ; i < 10 ; i++ )
   {
     
      third = first + second;
      cout<<third<<endl;
    
      first = second;
      second = third;
    }
   
   return 0;
}

Output :

0  1  1  2  3  5  8  13  21  34

Print Fibonacci Series in C


#include <stdio.h>

int main()
{
   int i, n, first=0,second=1,third;

   printf("Enter the number (No. of element you want to print in series) \n");
   scanf("%d",&n);
   
   /* Print first and second element. */
   printf("Fibonacci Series is \n");
   printf(" %d %d  ",first,second);


   for(i=2;i<n;i++){
  
     /* Print the sum of previous two element */

     third = first + second;
     printf(" %d ",third);

     first = second;
     second = third;
 }

return 0;
}


Output :


Enter the number (No. of element you want to print in series) : 8
Fibonacci Series is:   0  1   1  2  3  5  8  13 

No comments:

Post a Comment