Sunday, 12 May 2019

C PROGRAM TO PRINT N FIBONACCI SERIES (c++,java,python)

Fibonacci Series-

A Series of numbers in which each number is the sum of two preceding number in series

Fibonacci series always start with 0 and 1

ex-0 1 1 2 3 5 8 13 (0 1 0+1=1 1+1=2 2+1=3)

c program:

#include <stdio.h> //declaration of printf and scanf define in header file

int main()
{
  int first=0,second=1,next,n;//fibonacci series always start with o and 1

  printf("Enter the number of the term of Fibonacci series:");

  scanf("%d",&n);

  printf("%d\t%d",first,second);//first print the o and 1 then calculate sum in for loop 

  for(int i=1;i<=n;i++)

  {next=first+second; //add two consecative number result 1

      first=second;//now assign 1 in first variable

      second=next;//assign 1 in second variable 

    printf("\t%d",next);//print the sum values
  }

    return 0;
}

c++ program:

#include <iostream>//declaration of cin and cout

using namespace std;

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

  cout<<"Enter the number of the term of Fibonacci series:";

  cin>>n;

 cout<<first<<"\t"<<second;

  for(int i=1;i<=n;i++)

  {next=first+second;

      first=second;

      second=next;

    cout<<"\t"<<next;
  }

    return 0;
}

java program:

public class FibonacciSeries {

    public static void main(String[] args) {

    int n = 10, first = 0, second = 1;

    System.out.print("First " + n + " terms: ");

     for (int i = 1; i <= n; ++i)
      {
       System.out.print(t1 + " + ");

      int sum = t1 + t2;
      t1 = t2;
      t2 = sum;
    }
    }
}

python program:

n=int(input("Enter the number of term of fibonacci seires:"))

first=0

second=1

print(first,second,end=',')

for i in range(1,n+1):

    next=first+second

    first=second

    second=next

    print(next,end=',')


output:

No comments:

Post a Comment