 Explore Edit Edit

# Fibonacci series upto n value in C, C++, Java and Python | FACE Prep

Published on 10 Mar 2020

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 series upto 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 until 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 using Iterative method

C
C++
Java
Python 3

Output
Input- Enter the nth value: 1000 Output- Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

## Program to generate Fibonacci series upto n value using Iterative method & Command line

#include<stdio.h>
int main(int argc, char *argv[])
{
int sum = 0, n;
int a = 0;
int b = 1;
n = atoi(argv);
while(sum <= n)
{
printf("%d ", sum);
a = b; // swap elements
b = sum;
sum = a + b; // next term is the sum of the last two terms
}
return 0;
}


## Program to generate Fibonacci series upto n value using Recursive method

C
C++
Java

Output
Input- Enter the nth value: 1000 Output- Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

## Program to generate Fibonacci series upto n value using Recursive method & Command line

#include<stdio.h>
int Fibonacci(int n)
{
if (n <= 1)
return n;
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
int main(int argc, char *argv[])
{
int n, sum = 0;
n = atoi(argv);
while(Fibonacci(sum) <= n)
{
printf("%d ", Fibonacci(sum));
sum++;
}
}


Time complexity:O(n)

Recommended Programs  