Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: For Loop for Fibonacci code

1. ## For Loop for Fibonacci code

Hello Everyone,

I need to write a For Loop that prints out the first 12 Fibonacci numbers:
1 1 2 3 5 8 13 21 34 55 89 144.

The problem I am having is that I can not get the first two 1 numbers. I only get 1.2.3.5.8.....
```int a=1;
int b=1;
for (int i=1; i<12;i++)
{
System.out.print(a+" ");
a=a+b;
b=a-b;
}```

Do I need to add another For Loop that sub-tracks so that I can get the first digit of 1?

2. ## Re: For Loop for Fibonacci code

0,1,1,2,3,5,8....

I think it works if you change b to 0.

3. ## Re: For Loop for Fibonacci code

Whether the suggested approach is right or not, it should give you something to think about that will help you. Your current algorithm is unnecessarily complicated.

4. ## Re: For Loop for Fibonacci code

Thanks Hamenopi,

Changing B to =0 worked.