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

In the C program, recursion is used to print out some elements of the Fibonacci series. In the first line of the code, the stdio library is included within the program by the include keyword. Then inside the main() function, the fibonacci(int) function is declared that takes an integer as an argument. Three variables of the int integer type i,s and n are declared. The printf() function prints the string "Number of elements in the list : " and expects input from the user. This input is assigned to the variable n using the scanf() method.

Another printf() method prints the string "Fibonacci series is:n". Then a for loop is executed that initiates from 1 and goes until the value is less than n. Inside the loop the variable i is passed as the argument to the fibonacci() method, and the value is stored in the variable s. The value will be printed in the next line.
Then, the function fibonacci(int x) is defined. An integer variable f is declared. In the next line, an if statement checks whether the argument x is equal to 1. If the condition is True, 0 is returned. Else, is the x variable is equal to 2, 1 is returned. Otherwise, in the statement f= fibonacci(x-1)+fibonacci(x-2), the fibonaccci() function is called on the value of (x-1) and (x-2). The value is assigned in f and is printed out in the next line.

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

Within the main() function, variables of the integer type n1=0, n2=1, n3, number and i  are declared. The printf() method prints out the string "Number of elements in the list:" and asks for a value from the user. The value is stored in the variable called number. Next, the values of n1 and n2 are printed to the screen.

Then a for loop is executed that initiates with the value 2 and runs until the value of the iterator is less than the number specified by the user. Inside the loop, the variable n1 and n2 are concatenated and is stored in the variable n3. The printf() method prints out the value. Then, the value of n2 is assigned to variable n1. The value of n3 is assigned to the variable n2. The program ends with a return statement that returns 0.

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

Inside the main() function, the integer variable n, i, and fibonacci(int, int) function are declared in the first line of code. Then the printf() method prints out the string "Number of elements in the list:" and the input from the user is stored in the variable n. The next print statement prints out the numbers 0 and 1. The fibonacci(i,n) function is called in the next line.

The fibonacci() function is defined in the next line with two integer arguments m and n. Variables a=0, b=1 and c are declared. A for loop is executed, where the addition of a and b is stored in the variable c. Then the value of b is assigned to the variable a. The value of c is assigned to the variable b. The value of c is then printed.

As per the output, the user entered 4, so first, four digits of the Fibonacci series are printed. The resultant output is 0 1 1 2.

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

In this Java program, inside the main() function, the variables val1, val2, val3, loi and nxt of integer type are declared. The nxt variable is assigned with the value of 10. The val1 and val2 variables are assigned the values 1. The next statement System.out.print("Fibonacci Series "); prints out the string “Fibonacci Series” to the console. The next print statement displays the values of val1 and val2 variables.

The next line of code for(loi = 1; loi <= nxt-2; loi++), executes a for loop. Inside the variables, val1 and val2 are added together using the + operator. The value is assigned in the val3 variable. Then an empty string is printed. In the next line, the value of variable val3 is printed. Then the value of val2 is assigned to val1. At last, the value of val3 is assigned to val2. The final output after program execution is:
Fibonacci Series  1 1 2 3 5 8 13 21 34 55

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

In this program, the main() function has an integer return type. In the first line, variables i, nt, num1 = 0, num2 = 1 and nTerm of integer type are declared. The printf() method prints a string "Enter the number of terms: " and expects input from the user. The input is stored in the variable nt. The string "Fibonacci Series: " is printed in the subsequent line.

A for loop runs that starts from the iteration variable having the value of 1. This loop runs as long as the value is less than nt. Inside the loop, the value of the variable num1 is printed. Then the summation of num1 and num2 is added. This summation value is stored in the variable called nTerm. The code assigns the value of num1 to the num1 variable. The value of the nTerm variable is stored in the num2 variable.

The last line returns a value of 0. 

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 number of elements in the Fibonacci series is obtained from the user using the input() method. This value is converted from a string to an integer by using the int()  method and is stored in the loopterms variables. Then the variable num1 is assigned the value of 0. The variable num2 is assigned the value of 1. The total variable is initialized with the value of 2.

Then an if statement checks whether the loopterms variable has a value less than or equal to 0. When the condition is True, the string "Please enter a positive integer" is printed. Else, if the loopterms variable has a value of 1, the string “Fibonacci sequence” is printed. The value of the num1 variable is printed. Otherwise, the string “Fibonacci sequence” is printed. In the next line, the print(num1,",",num2,end=', ') displays the value of num1, num2 and blank spaces in between them.

Then, inside this else condition a while loop checks whether the total variable is less than the loopterms variable. While the condition is True, the num1 and num2 variable are added. The value is stored in the nth variable. The variable is then printed out. The num2 variable value is assigned to the num1. Next, the nth variable value is assigned to the num2 variable.
The last line increments the total variable by 1.

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

In this C++ program, the library iostream is included using the #include statement. Inside the main() function, the integer variables num1 = 0,i=2, num2 = 1, nTerm = 0, nput; are declared. A cout statement displays the string "Enter a positive number: "; to obtain a value from the user. The value obtained is stored in the nput variable. Another cout statement displays the variable values of num1 and num2 that are 0 and 1 respectively. Then the num1 and num2 variables are added and stored in the nTerm variable.

Then a while loop checks whether the variable i is less than the nput variable. Inside the loop body, the i variable is incremented by 1. A cout statement prints the nTerm value. The value of num2 is assigned to the num1 variable. The nTerm variable value is assigned to the num2 variable. Then, the variables num1 and num2 variables are added and stored in the nTerm variable.
The last line of the code returns 0.

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.