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
Input:10
Approach
- 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.
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:
- a=0
- i=1
- i=2
- i=3
- i=4
- i=5
- i=6
- i=7