Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!

Fibonacci

Todd Smith Todd
Greenhorn
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;

//***************************************************
//***************************************************
System.in));

//***************************************************
// Get first Fibonacci number from user
//***************************************************
System.out.print("Enter Fibonacci number: ");

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

System.out.print("Enter Fibonacci number: ");

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