TechArena Community java coding for fibonacci series

#1
17-11-2009
 Member Join Date: Jan 2009 Posts: 37
java coding for fibonacci series

Hi friends,

I am BSc(I.T) student. I have to write fibonacci series program using java programming.I have written the code but when I run the program either I get wrong result or unknown compile time error.

Can anybody provide me the source code for the fibonacci series even the hint also will works for this???
#2
17-11-2009
 Member Join Date: May 2008 Posts: 2,008
Re: java coding for fibonacci series

I used below code to get Output as a fibonacci series:

Quote:
 package com.gpt; import javax.swing.JOptionPane; /* This program computes Fibonacci numbers using a recursive method. */ public class Fibonacci { public static void main(String[] args) { String input = JOptionPane.showInputDialog("Enter n: "); int n = Integer.parseInt(input); for (int i = 1; i <= n; i++) { int f = fib(i); System.out.println("fib(" + i + ") = " + f); } System.exit(0); } /** Computes a Fibonacci number. @param n an integer @return the nth Fibonacci number */ public static int fib(int n) { if (n <= 2) return 1; else return fib(n - 1) + fib(n - 2); } }
#3
17-11-2009
 Member Join Date: Apr 2008 Posts: 2,001
Re: java coding for fibonacci series

It is very easy code.I don't thing that you will get errors for below code:

Quote:
 public class FibonnaciSeries { public void generateSeries(int num) { int f1, f2 = 0, f3 = 1; System.out.println(?fib(0) = ? + f2); for (int i = 1; i <= num; i++) { System.out.println("fib(" + i + ") = " + f3); f1 = f2; f2 = f3; f3 = f1 + f2; } } public static void main(String[] args) { System.out.println("*****Fibonnaci Series*****"); FibonnaciSeries fb = new FibonnaciSeries(); fb.generateSeries(10); } } The Output of above program will be: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55
#4
17-11-2009
 Member Join Date: May 2008 Posts: 2,293
Re: java coding for fibonacci series

Have you used below logic???...

//Below program require user input
Quote:
 public class fibonacci { public static void main(String args[]) { int prev1 = 1, prev2 = 1, current = 1;int n; n = System.read("enter number: "); for (int i = 3; i <= n; i++) { current += prev2; prev2 = prev1; prev1 = current; System.out.println(" " + current); } } }

Last edited by Zecho : 17-11-2009 at 10:46 AM.