Wednesday, November 11, 2015

Fibonacci Series Program in java with Exaplanation

In this post we will learn how to write a Fibonacci Series java program. This is frequently asked in technical round in interview to test your programming logic.In this post we will discuss Fibonacci in two ways using recursion and using for loop.

Fibonacci Series means Sum of Previous two numbers will give us next number(1 1 2 3 5 8)

fibonacci series logic: 

Sum of Previous two numbers will give us next number


prev                   next                                  sum
                   shifted to prev                    shifted to next
1                   1                                            2
1                         2                                            3
2                      3                                            5
3                         5                                            8
5                         8                                           13
13                      ----                                        ----

 
Note:  prev will give you fibonacci series

Program:

class Fibonacci{
public static void main(String args[])
{ 
int prev, next, sum, n;
prev=next=1;
for(n=1;n<=10;n++){
System.out.println(prev);
sum=prev+next;
prev=next;
next=sum;
}
}
}
    
Output:   











Fibonacci N Series Program Using Recursion:

import java.util.Scanner;
class calc{
int fibo(int n){
if(n==0)
return 0;
 if(n==1)
 return 1;
 else
return fibo(n-1)+fibo(n-2);
 }
}
public class Fibonacci{
public static void main(String[] args){  
Scanner sc=new Scanner(System.in);
System.out.println("Enter fibonacci Number :");
int n=sc.nextInt();
System.out.println("Fibonacci Series is :\n");  
calc c=new calc();  
for(int i=0;i<n;i++){
System.out.print("   "+c.fibo(i)); 
}
}
}

Output:






I hope you enjoy this post and share this to your friends and social websites and also write comments on this topic, keep follow me for latest updates 

No comments:

Post a Comment

High Paying Jobs after Learning Python

Everyone knows Python is one of the most demand Programming Language. It is a computer programming language to build web applications and sc...