0
public class fibonacci
{
    public static void main(String[] args)
    {
        int a=0,b=1,c=2;
        while(a<4000000)
        {
            a=b;
            b=c;
            c=a+b;
            System.out.println(a);
        }
    }   
}

Trying to print Fibonacci series less than 400000, but it is printing 5702887 as well.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • 2
    Because you are incrementing `a, b, c` before printing? – Andrew Li Jul 29 '18 at 14:52
  • Mathematically, Fibonacci sequence starts like this: `1, 1, 2, 3...`. But from the programmers perspective sequence starts with zero: `0, 1, 1, 2, 3`... I'd recommend you to take a few minutes and read [this](https://www.geeksforgeeks.org/program-for-nth-fibonacci-number/) – zlakad Jul 29 '18 at 17:20

3 Answers3

3

Rearrange the printing and the checking, so that both act on the same value

int a=1,b=1,c=2;
while(a<4000000)
{
    System.out.println(a);
    a=b;
    b=c;
    c=a+b;        
}

This outputs the fibonacci sequene, with two times "1" at the start.
If you want "1, 2, 3..." use

int a=1,b=2,c=3;
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
0

Fibonacci series start from 1. look at this. I gave solution for your code. You set a=b after check a<4000000. then you need to check with b.

int a=0,b=1,c=2;
    while(b<4000000)
    {
        a=b;
        b=c;
        c=a+b;
        System.out.println(a);
    }
GolamMazid Sajib
  • 8,698
  • 6
  • 21
  • 39
0

your code is fine all you have to do is to put the print statement before calculating the next number because 3524578 <5702887

I'mDoneOK
  • 39
  • 2
  • 9
  • Please highlight the addtional insight of this answer, in comparision to the other answers, especially the one already proposing printing before checking (which admittedly is mine). You might want to mention the different behaviour, apparent in the additional "0" which will be printed by your proposal and refer to a definition of the fibonacci sequence which includes that additional initial number. A discussion of the start of the sequence intended by OP (fibonacci or not) might help understanding the consequences. – Yunnosch Jul 29 '18 at 16:22