need some help doing loops with fibonacci sequence

a bit confused here. i set one variable to 0 and the other to 1. I then ask the user how many elements they wish to only count up to. i guess the way this problem was written up is confusing me even more. im trying to figure out how to finish this. basically if the user only wants the first 5 numbers of the sequence, i then need to print it out. i was going with a for(x,y,z++) but im not sure if it is appropriate in this case. any help would be appreciated

Code:

`import java.util.Scanner;`

public class FibonacciSequence {

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

Scanner input= new Scanner(System.in);

long prevNum=0;

long newNum=1;

System.out.print( "Enter number of elements: ");

int element= input.nextInt();

System.out.println(prevNum + " " + newNum +" " + element);

for(int i=0;i<=element;i++){

long tempVal

Re: need some help doing loops with fibonacci sequence

The first question I might ask is whether you understand what a Fibonacci sequence is and how to construct one on paper.

Regards,

Jim

Re: need some help doing loops with fibonacci sequence

Quote:

Originally Posted by

**jim829** The first question I might ask is whether you understand what a Fibonacci sequence is and how to construct one on paper.

Regards,

Jim

i know it goes 0 1 1 2 3,etc. adds the previous two numbers.

Re: need some help doing loops with fibonacci sequence

Exactly! So you need to put that inside a loop. The currentValue is the sum of the previous two. Then you need to update the previous two.

Regards,

Jim

Re: need some help doing loops with fibonacci sequence

sorry jim, you lost me lol

im supposed to have the user choose how long this sequence goes to. if he says he only wants the first 5 numbers, then thats how far itll be. Does that go inside the for loop?

Re: need some help doing loops with fibonacci sequence

The first five numbers just means the first five of the sequence (at least that's my interpretation). But the sequence always starts out with 0 and 1. So the first five would be 0 1 1 2 3. The first eight would be 0 1 1 2 3 5 8 13. The hard part is figuring out how to update the variables inside the loop to continue calculating the next value in the series. It helps to try this on paper with some variables.

Regards,

Jim

Re: need some help doing loops with fibonacci sequence

ok i just had it clarified. what i didnt understood was i needed a tempValue.

so tempVal=newElement;

newElement=prevElement+ newElement;

prevElement=tempVal;

i was confused if that was going into the loop or not.