Write a program for the given number is Fibonacci in java?

Fibonacci series Program In java:

The fibonacci series sum of previous two numbers , come in next number for example 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,89,144 etc. The fibonacci series of first two numbers are 0 and 1.

We can write the fibonacci series program in two ways. There are
(i)The Fibonacci Series without using recursion
(ii)The Fibonacci Series using recursion

(i)Fibonacci Series in Java without using recursion

public class Fibonacci
{
public static void main(String args[])
{
int n,f1=0,f2=1,f,count=0;
System.out.println(“enter the n value ;”);
Scanner s= new Scanner(System.in);
n=s.nextInt();
if(n==0){
count++;
}
else{
while((f=(f1+f2))<=n)
{
if(f==n)
{
count=1;
break;
}
f1=f2;
f2=f;

}
if(count==1)
{
System.out.println(“the given number is fibonacci”+n);
}
else
{
System.out.println(“the given number not a fibonacci number:”+n);
}
}
}

output:
Enter the n value:10
The given number is a fibonacci
0,1,1,2,3,5,8,13,21,34

(ii)Fibonacci Series using recursion in java
Let’s see the fibonacci series program using recursion in java.

class FibonacciExam2{
static int p=0,q=1,r=0;
static void printFibonacci(int count){
if(count>0){
r = p + q;
p = q;
q = r;
System.out.print(” “+r);
printFibonacci(count-1);
}
}
public static void main(String args[])
{
int count=12;
System.out.print(p +” “+q);//printing 0 and 1
printFibonacci(count-2);//n-2 because 2 numbers are already printed
}
}

Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,55,89,144,233

Related Programs Below:
Write a program the given number is even or odd in java?
Write a program for the given number is Fibonacci or not in java?
Prime numbers in Java?
Palindrome number Program in java?
Armstrong Number or not in Java?
Write a program for the given number is strong Number or Not  in java?
Write a program swapping two numbers without using third variable in java ?
Swapping of two numbers using third variable in java?

Leave a Reply

Your email address will not be published.