Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Fibonacci  RSS feed

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
}
}
}
 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Those who dance are thought mad by those who hear not the music. This tiny ad plays the bagpipes:
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!