Thursday, 22 September 2016

Java Program For Fibbonacci Series ?

Previously we have discussed the Program for 
Java Program to read all Files from Directory or Sub Directory For Some Period of time ?

Fibonacci series is a sequence of numbers in which next number is obtained by adding previous two numbers. Here We assume First two numbers of Fibonacci series are 0 and 1. In this Program the loop starts from 2 because first two elements we have already taken i.e 0 and 1.

There are many ways to print Fibonacci series in java like for-loop, while-loop, do-while loop, and using recursive method. In below program i have discussed all the ways.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public class FibbonacciExample {
 
 public static void usingForLoop(int count){
  System.out.println("USING FOR LOOP : ");
  int a=0;
  int b=1;
  System.out.print(a+","+b+",");
  for(int i=0;i<10;i++){
   int c=a+b;
   a=b;
   b=c;
   System.out.print(c+",");
  }
 }
 public static void usingWhileLoop(int count){
  System.out.println("\n\nUSING WHILE LOOP : ");
  int a=0;
  int b=1;
  System.out.print(a+","+b+",");
  while(count > 0){
   int c= a+b;
   a=b;
   b=c;
   System.out.print(c+",");
   count--;
  }
 }
 public static void usingDoWhileLoop(int count){
  System.out.println("\n\nUSING DO-WHILE LOOP : ");
  int a=0;
  int b=1;
  System.out.print(a+","+b+",");
  do{
   int c = a+b;
   a=b;
   b=c;
   System.out.print(c+",");
   count--;
  }
  while(count>0);
 }
 public static int usingRecursiveMethod(int count,int a,int b){
  if(count > 0){
   int c = a+b;
   a=b;
   b=c;
   System.out.print(c+",");
   count--;
  }
  else{
   return 0;
  }
  return usingRecursiveMethod(count,a,b);
 }
 public static void main(String[] args) {
  FibbonacciExample.usingForLoop(10);
  FibbonacciExample.usingWhileLoop(10);
  FibbonacciExample.usingDoWhileLoop(10);
  System.out.println("\n\nUSING RECURSIVE METHOD : ");
  FibbonacciExample.usingRecursiveMethod(10,0,1);
 }
}

Output :-

USING FOR LOOP :
0,1,1,2,3,5,8,13,21,34,55,89,

USING WHILE LOOP :
0,1,1,2,3,5,8,13,21,34,55,89,

USING DO-WHILE LOOP :
0,1,1,2,3,5,8,13,21,34,55,89,

USING RECURSIVE METHOD :
1,2,3,5,8,13,21,34,55,89,


No comments:

Post a Comment