Fibonacci series upto n value in C, C++, Java and Python | faceprep

Program to generate Fibonacci series upto n value is discussed here. Fibonacci series is a series in which each number is the sum of the last two preceding numbers. The first two terms of a Fibonacci series are 0 and 1.

For example, generate fibonacci series upto 200.

The first two terms are 0 and 1.

  • 0 + 1 = 1
  • 1 + 1 = 2
  • 1 + 2 = 3
  • 2 + 3 = 5
  • 3 + 5 = 8
  • 5 + 8 = 13
  • 8 + 13 = 21
  • 13 + 21 = 34
  • 21 + 34 = 55
  • 34 + 55 = 89
  • 55 + 89 = 144
  • 144 + 89 = 233

The fibonacci seriesnto 200 is given as follows.

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144.

Algorithm to generate Fibonacci series upto n value

  1. Input the n value upto which the Fibonacci series has to be generated.
  2.  Initialize sum = 0, a= 0 and b = 1
  3. Print the first two terms of the series, a and b.
  4. sum = a + b
  5. If(sum < n)
  6. print (sum)
  7. swap a and b and swap b and sum.
  8. If (sum > n)
  9. End the algorithm.
  10. Else 
  11. Repeat from steps 4 to 7.

Program to generate Fibonacci series upto n value

// C program to generate fibonacci series upto n value

#include

int main()
{
int i,c=0,n;
int a=0;
int b=1;
printf(“\nEnter the nth value : “);
scanf(“%d”,&n);
printf(“\nFibonacci series : “);
while(c<=n)
{
printf(“%d “,c);
a=b;   // swap elements
b=c;
c=a+b; // next term is the sum of the last two terms 
}
printf(“\n”);
return 0;
}

// C++ program to generate fibonacci series upto n value

#include<iostream>
using namespace std;

int main()
{
int i,c=0,n;
int a=0;
int b=1;
cout << “\nEnter the nth value : “;
cin >> n;
cout << “\nFibonacci series : “;
while(c<=n)
{
cout << c << ” “;
a=b;
b=c;
c=a+b;
}
cout << endl;
return 0;
}

// Java program to generate fibonacci series upto n value

import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter the nth value : “);
int n = sc.nextInt();
int a=0;
int b=1;
int c = a+b;
System.out.print(“\nFibonacci series : “);
while(c<=n)
{
System.out.print(c + ” ” );
a=b;
b=c;
c=a+b;
}
}
}

# Python program to generate Fibonacci series upto n value

n = int(input(“Enter the nth value: “))
a = 0
b = 1
c = 0
print(“Fibonacci Series : “,end = ” “)
while(c <=n):
print(c,end = ” “)
a = b
b = c
c = a + b

 

 

#include<stdio.h>
#include<math.h>
int main(int a, char *b[])
{
int i, n, t1 = 0, t2 = 1, nextTerm;
n=atoi(b[1]);
for (i = 1; i <= n; ++i)
{
printf(“%d “, t1);
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
}
return 0;
}

Output:

fibonacci series upto n value

Time complexity: O(n)