• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Fibonacci

 
RH Gomez
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I'm having some trouble with a program I'm trying to write.. in theory I know what to do but my code seems to have more than one error. The program must ask the user for a number (n) and return the first n numbers of the fibonacci sequence. Any help will be apreciated.
This is the code

import acm.program.*;

public class ProgramaFibonacci extends ConsoleProgram {

public static void main(String[] args) {
new ProgramaFibonacci().start();
}

public void run() {

int n = this.readInt("Dame un n�mero entero: ");

int n1 = 1;
int n2 = 1;
int i = 2;

if ((n == 0) || (n == 1)) {
n1 = 1;
} else {
for (i = 2; i <= n; i++) {
n1 = n2 + i;
i = n2;
n2 = n1;

}
}
return n;
}

}
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, please use CODE tags to keep your formatting intact. Here is your code (as you entered it) with tags...

Now, to see what's happening, take a look at the for loop, and consider what happens on the first iteration (when n1 and n2 both start as 1, and i is 2)...
n1 = n2 + i; //n1 = 1 + 2 = 3
i = n2; //i = 1
n2 = n1; //n2 = 3

Hmmm... Is that what you want? Both n1 and n2 to end up equal? Look at the next iteration (after i has been incremented to 2)...
n1 = n2 + i; //n1 = 3 + 2 = 5
i = n2; //i = 3
n2 = n1; //n2 = 5

And then (after i has been incremented to 4)...
n1 = n2 + i; //n1 = 5 + 4 = 9
i = n2; // i = 5
n2 = n1; //n2 = 9

Basically, you're using the variable i as a counter, to count from 2 to n. But within your for loop, you're assigning i a different number. I think you would do better using n1 and n2 to store your sequence values, and leave i alone to count.

Also, when you're done, you probably don't want to return n.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another tip: You should give your variables more descriptive names. This makes it easier for others to read your code, and it also might help you to keep things straight.

For example, instead of n, i, n1, and n2, you might use limit, iteration, currentNumber, and previousNumber.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic