fibonacci.java

on 2:15 PM

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);
}
}

0 comments:

Post a Comment