BlogsDope image BlogsDope

Fibonacci series in Java

Feb. 28, 2021 JAVA ALGORITHM DATA STRUCTURE RECURSION 3113

The Fibonacci series is a series of numbers where a number is the addition of the last two numbers, starting with 0, and 1.

The Fibonacci Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55…

Starting with 0 and 1 as the first and second terms, the third term is addition of the first two i.e., 0+1; third term is addition of the first and third terms i.e., 1+1 and so on.

Problem Description

Write a Program to display the user-defined N number of the Fibonacci series terms.

​Input:7

       Output:0 1 1 2 3 5 8

Input:10

       Output:0 1 1 2 3 5 8 13 21 34

Approach

The Fibonacci numbers are the numbers in the sequence such that the current number will be the sum of the previous two numbers i.e., F(n) = F(n-1) + F(n-2).
And given that F(1)=0 and F(2)=1.
  • ​Take the number as input from the user.
  • Initialize the first number with 0 and the second number with 1. 
  • Now, start moving iteratively till the Nth number. To calculate the current number, equate it to sum of the previous two numbers. And continue to move further.

Pseudocode

Input=N
a=0
b=1
For i=1 till i less than equal to N:
    print(a)
    c=a+b
    a=b
    b=c

Let's run few iterations of this code.

Initially, we will have the sequence 0, 1. In the first iteration, c will be the next term and we will change the values of a and b.

Proceeding with the next iteration, c will again be the next term and again a and b will be updated as shown below.

Fibonacci series calculation steps
Fibonacci series calculation steps

Program

package codesdope;
import java.util.*;
public class codesdope 
{
   public static void main(String[] args)
   {
	Scanner sc=new Scanner(System.in);
	int count=sc.nextInt();
       int num1 = 0, num2 = 1;
       for(int i=1;i<=count;i++)
       {
            System.out.print(num1+" ");
            int sum = num1 + num2;
            num1 = num2;
            num2 = sum;
       }
   }
}

10

0 1 1 2 3 5 8 13 21 34 

Let us dry run the code:

For N=7
  • a=0
       b=1
  • i=1
       print(a)=0
       c=a+b=1
       a=b=1
       b=c=1
  • i=2
       print(a)=1
       c=a+b=2
       a=b=1
       b=c=2
  • i=3
       print(a)=1
       c=a+b=3
       a=b=2
       b=c=3
  • i=4
       print(a)=2
       c=a+b=5
       a=b=3
       b=c=5
  • i=5
       print(a)=3
       c=a+b=8
       a=b=5
       b=c=8
  • i=6
       print(a)=5
       c=a+b=13
       a=b=8
       b=c=13
  • i=7
      print(a)=8
      c=a+b=21
      a=b=13
      b=c=21

Liked the post?
Editor's Picks
0 COMMENT

Please login to view or add comment(s).