Java program of the Fibonacci series

 

Fibonacci series program in java language:

 

 

In this article, you’ll learn how to create the Fibonacci series program in java language to print first N terms of Fibonacci series, without giving input from the keyboard or giving input from the keyboard.

Q: What is the Fibonacci series.

Ans:  A series of number in which each number is the sum of the two preceding numbers is known as Fibonacci series. In Fibonacci series two number is fixed i.e., 0 and 1 then we create the third number by adding the previous two number.

A simple example of Fibonacci series 0,1,1,2,3,5,8,13, etc. here each number is the sum of the previous two number.

Q: Write a program in java language to print first x term of Fibonacci series, without input from the keyboard, the value of x is 7.

Solution:

public class fibos {

public static void main(String args[]) {

int n1=-1,n2=1,x=7,i,temp;

for(i=1;i<=x;i++)

{

temp=n1+n2;

System.out.print(“ “temp);

n1=n2;

n2=temp;

 

}}}

 

The output of this program:

0 1 1 2 3 5 8

Note: In the above program we take five variable n1 =-1 , n2 =1, x=7, i and temp. here we take n=-1 and n2=1 with the sum of n1 and n2 we get the first number of the Fibonacci series, then store the sum in the temp variable. Variable i is used for loop and its initial value is 1 rotates up to value of x. for this program the value of x is 7, it means you want to show a Fibonacci series which have 7 number.

 

Q: Write a program in java language to print first x term of Fibonacci series, with input from the keyboard, the value of x is decided by the user.

Solution:

import java.util.Scanner;

public class  fibos {

public static void main(String args[]) {

int n1=-1,n2=1,i,temp;

System.out.print(“Enter how many numbers you want to print: “);

Scanner sc=new Scanner(System.in);

int x=sc.nextInt();

sc.close();

for(i=1;i<=x;i++)

{

temp=n1+n2;

System.out.print(” “+temp);

n1=n2;

n2=temp;

 

}}}

 

The Output of this program:

Enter how many numbers you want to print: 16

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610

You may also learn the following programming:

Leave a Reply

Your email address will not be published. Required fields are marked *