Online Tutorials & Training Materials | STechies.com
Register Login

Fibonacci Series Program in Java, Python, C, C++

05 Jan 2018 1:49 pm || 0

What is the Fibonacci Series?

A Fibonacci series is a sequence of numbers where each number is the sum of the previous two numbers. The series starts from two numbers 0 and 1. They are in the fowling sequence:

This series generates next number in series by adding the previous two numbers. It starts the sequence of series using two numbers − F0 & F1. With the starting values of F0 & F1 to start the series 0, 1 or 1, 1 respectively.

either 
0,1,1,2,3,5,8,13,21,34,55,.,.,.,.,.,.,. and so on

or if it starts with 1 then
1,1,2,3,5,8,11,19,30,49,79........ and so on.

Fibonacci Series Examples

In mathematical terminology, each number is in the form of:

Fn = Fn-1 + Fn-2

In this tutorial, we will Study

Fibonacci Series Algorithm

Fibonacci sequence algorithm starts with 1 we can write it as

sq (1) = sq (0) = 1.

sq (n) = sq ( n-1 ) + sq ( n-2 )  for n >= 2

Fibonacci numbers starts with (starting sq (0))  1, 1, 2, 3, 5, 8 ...

simply we can say the n-th Fibonacci number is the sum of the prior 2. As said in the explanation.

If you want to start with 0 then you have assigned 0 to sq (1)=sq(0)=0.

To understand in the elaborated way of Algorithm

1) Start

2) Variables Declaration L, A, B, display

3) Value assign to variables, A=0, B=1, and Display =0

4) Assign the series sequence to be run

5) Print starting two number terms of series using variable previously caring values 0,1 (in A, B respectively).

6) Start the loop using the loop variable

  • -> Display =A+B
  • -> A=B
  • -> B=Display
  • -> increase loop value of L by 1
  • -> print the value of Display

7) End

Fibonacci Series Methods

There are 2 methods to Display Fibonacci Sequence:

  1. Fibonacci Series using Recursion
  2. Fibonacci Series without Recursion

1) Fibonacci Series using Recursion in C

#include<stdio.h>
void main()
{
int fibonacci(int ) ;
    int i,s,n;
    printf("Number of elements in the list : ");
    scanf("%d",&n);
    printf("Fibonacci series is :n");
    for(i=1;i<=n;i++)
    {
 s= fibonacci(i);// Calling with Argument
 printf("%5d",s);
   }
getch();
}

// Function definition
int fibonacci(int x)
{
 int f;
 if (x==1)
  return(0);
 else if (x==2)
 return(1);
else
f= fibonacci(x-1)+fibonacci(x-2);
 return(f);
}

Output

Number of elements in the list: 5

Fibonacci series is: 0 1 1 2 3 5

Fibonacci series is:

0 1 1 2 3

Explanation

We know that recursion happens when a function that calls itself. Within the main() function, the fibonacci() method is called with the i argument, and the result is printed. But the actual recursion can be observed within the function definition, right outside the main() function. At first it is checked whether the argument is 0 and 1. If the statements are evaluated to True, the numbers 0 and 1 will be returned, that are the initial two numbers of the Fibonacci series.    
  
In the next statement f= fibonacci(x-1)+fibonacci(x-2), we can see that the fibonacci() method is recursively invoked two times with (x-1) and (x-2). Both these arguments indicate the fact that the initial two numbers of the series are already printed, and hence the printing will continue from the next number. Therefore, the final value stored in the variable f is printed out as – 0 1 1 2 3

2) Fibonacci Series without Recursion in C

#include<stdio.h>    
int main()    
{    
 int n1=0,n2=1,n3,i,number;    
 printf("Number of elements in the list:");    
 scanf("%d",&number);    
 printf("n%d %d",n1,n2);   
 for(i=2;i<number;++i)  
 {    
  n3=n1+n2;    
  printf(" %d",n3);    
  n1=n2;    
  n2=n3;    
 }  
  return 0;  
 }    

Output

Number of elements in the list: 5

Fibonacci series is: 0 1 1 2 3

Explanation

In this program, the initial two values of the Fibonacci series are printed out in within the main() method. For the other numbers, no recursion is used. As we know that the Fibonacci series consists of numbers, where each number is the sum of the previous two numbers. So, as the first two numbers are 0 and 1, the next number will be 1.

Within the for loop, the first two numbers stored in n1 and n2 are added and stored in n3. Then the two variable values of n1 and n2 are replaced with new values of n2 and n3. So the fourth number in the series will be 2, as the previous digits 1 and 1 are added. This loop continues until the number of elements specified by the user is printed out. 

3) Fibonacci Series using Function

#include<stdio.h>
void main()
{
int fibonacci(int,int),n,i;
printf("Number of elements in the list:");
scanf("%d",&n);
printf("  0  1");
fibonacci(i,n);
getch();
}
int fibonacci(int m,int n)
{
int a=0,b=1;
int c;
for(m=1;m<=n-2;m++)
{
c=a+b;
a=b;
b=c;
printf("t%d",c);
}
}

Output

Number of elements in the list: 4

Fibonacci series is:

0 1 1 2

Explanation

In this program, the Fibonacci series is printed out using a user-defined function called fibonacci(). Inside this function, a for loop is runs. The number of times the loop will run will be equal to the number of elements the user wants in the Fibonacci series. The loop is initialized at m=1 and runs until the value m<= n-2, as the first two numbers of the series are already printed. Then inside the loop, the first two values are added to get the next element. This is because the Fibonacci series consists of numbers, where each number is the sum of the previous two numbers. So, as the first two numbers are 0 and 1, the next number will be 1.

The loop works until the number of elements specified by the user are displayed.       

Fibonacci Series Java Program Example

public class Main {
 public static void main(String args[]) {
 int val1, val2, val3, loi, nxt;
 nxt = 10;
 val1 = val2 = 1;
 System.out.print("Fibonacci Series ");
 System.out.print(val1+" "+val2);
 for(loi = 1; loi <= nxt-2; loi++) {
 val3 = val1 + val2;
 System.out.print(" ");
 System.out.print(val3);
 val1 = val2;
 val2 = val3;
 }
 }
}

Output will be

$javac FibSeries.java
$java -Xmx128M -Xms16M FibSeries
Fibonacci Series  1 1 2 3 5 8 13 21 34 55

Explanation

Let us understand the code written above. Here, the Fibonacci series starts from 1, and the initial two digits 1 and 1 are printed. Then a for loop is executed that initiates from loi=1. It runs upto the value loi<=nxt-2, as the first two digits of the series are already printed. Thus, the loop has to print two less numbers for the series.

Then, as per the Fibonacci series logic, the first two numbers stored in val1 and val2 are added to get the third number that is stored in the variable val3. So, the values of val1 and val2 changes. Then, the new values of val1 and val2 are added to find the next number in the series. The process continues until the loop condition loi<=nxt-2 is satisfied.      

Fibonacci Series in C

#include <stdio.h>

int main()

{
 int i, nt, num1 = 0, num2 = 1, nTerm;

 printf("Enter the number of terms: ");

 scanf("%d", &nt);

 printf("Fibonacci Series: ");
 for (i = 1; i <= nt; ++i)

 {
 printf("%d, ", num1);

 nTerm = num1 + num2;

 num1 = num2;

 num2 = nTerm;

 }

 return 0;

}

Output will be

Enter the number of terms: 12                                                                                                 

Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,  

Explanation

Here, at first, the number of elements required for the Fibonacci series is obtained from the user. This value stored in the nt variable is the number of times the for loop will run. Inside this loop, after the first element 0 is printed, the first and second element is added to get the next element of the series. Thus, new values of num1 and num2 are replaced with old values.

The loop works as long as the loop condition is satisfied, i.e i<=nt.         

Fibonacci Series Python Example

# To print Fibonacci series, after taking no of terms input from user
loopterms = int(input("Please enter the Loop Terms : "))
num1 = 0
num2 = 1
total = 2
if loopterms <= 0:
 print("Plese enter a positive integer")
elif loopterms == 1:
 print("Fibonacci sequence:")
 print(num1)
else:
 print("Fibonacci sequence:")
 print(num1,",",num2,end=', ')
 while total < loopterms:
  nth = num1 + num2
  print(nth,end=' , ')
  num1 = num2
  num2 = nth
  total += 1

Output will be 

Please enter the Loop Terms : 10                                                                                                            

Fibonacci sequence:                                                                                                            
0 , 1, 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 , 

Explanation

The main part of the code is the while loop. Here, after evaluating whether the while condition is True or False, the first two numbers, num1 and num2, are added to obtain the third element of the series. Then, the values of num1 and num2 are interchanged with the new values. Therefore, num2 becomes the new num1 and nth becomes the new num2. They are added again to get the next element in the series.

The process goes on until the total variable is less than loopterms variable.   

Fibonacci Series C++ Program Example

#include <iostream>

using namespace std;

int main()

{
 int num1 = 0,i=2, num2 = 1, nTerm = 0, nput;

 cout << "Enter a positive number: ";

 cin >> nput;

 // displays the first two terms which is always 0 and 1

 cout << "Fibonacci Series: " << num1 << ", " << num2 << ", ";

 nTerm = num1 + num2;

 while(i < nput)

 {
 ++i;

 cout << nTerm << ", ";

 num1 = num2;

 num2 = nTerm;

 nTerm = num1 + num2;
 }

 return 0;

}

Output will be 

Enter the number of terms: 12                                                                                                 

Fibonacci Series:  01 1 2 3 5 8 13 21 34 55 89

Explanation

Let us try to get into the details of the code. In the first section of the code, the initial two terms 0 and 1 are printed. Then they are added to get the third element, 1. Inside the while loop, the third element stored in the nTerm variable is printed out. The values of num1 and num2 are assigned the current values of num2 and nTerm. These new values of num1 and num2 are again added to produce the fourth element of the Fibonacci series.

The while loop will run until the value of the variable i has a value less than the variable input.    

Conclusion

The Fibonacci series is a very popular program Java, Python, C and C++. But if you are using recursion, make sure that you are calling and defining the functions properly.