aspose file tools*
The moose likes Java in General and the fly likes Fibonacci Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Fibonacci" Watch "Fibonacci" New topic
Author

Fibonacci

Todd Smith Todd
Greenhorn

Joined: Dec 11, 2002
Posts: 4
I am trying to change this code to produce output like Example
If the user enters 6, program should display the numbers 1 1 2 3 5 8 not just 8.
If the user enters 2, program should display the numbers 1 1 not just 1.
I am have troubles can any one help. This assigment is killing me I am sure it is just some thing I am over looking.


//************************************************************
//Fibonacci.java
//Todd M. Smith
//Intro to Java Programming CIPT 190
//Lab 13
//A program that uses a recursive method to display the first
//numbers of the Fibonacci sequence input by the user.
//************************************************************

import java.io.*;

public class Fibonacci
{
public static void main(String args[]) throws IOException
{
int theNum, theFib;

//***************************************************
// Set up buffer reader
//***************************************************
BufferedReader stdin = new BufferedReader(new InputStreamReader(
System.in));

//***************************************************
// Get first Fibonacci number from user
//***************************************************
System.out.print("Enter Fibonacci number: ");
theNum = Integer.parseInt(stdin.readLine());

theFib = fib(theNum);

System.out.println("The " + theNum + "th Fibonacci " +
"number = " + theFib + ".");
}
static int fib(int k) {

// Base Case:
// If k <= 2 then fib(k) = 1.
if (k <= 2) {
return 1;
}
// Recursive Case:
// If k > 2 then fib(k) = fib(k-1) + fib(k-2).
else {
return fib(k-1) + fib(k-2);
}
}
}
Naani Mui
Greenhorn

Joined: Oct 03, 2004
Posts: 12
You need to use loop to print all the values.

Try with the following code:

import java.io.*;

public class Fibonacci
{
public static void main(String args[]) throws IOException
{
int theNum, theFib;

BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

System.out.print("Enter Fibonacci number: ");
theNum = Integer.parseInt(stdin.readLine());

for(int p=1;p<=theNum;p++)
{
theFib = fib(p);
System.out.print(theFib+", ");
}

}

static int fib(int k)
{
if (k <= 2) {
return 1;
}
else {
return fib(k-1) + fib(k-2);
}
}
}

I have just added the loop statement to your code.

Hope this helps.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Fibonacci