Why does my for loop return only half the elements I expect it to?

Viewed 39

I would like to receive user input on n elements for the Fibonacci sequence. The scanner and calculations themselves seem to be working fine -- the input is successfully grabbed and the sequence calculated. It's even able to correctly disqualify inputs of a negative value. However, it is not actually returning 'n' elements. Curiously, I noticed that the loop consistently returns exactly half the elements requested, albeit in the correct order. If n = 20, the first 10 numbers are returned.

Here's the code:

public class fibonacci_input {

    public static void main(String[] args) {
// TODO Auto-generated method stub

        Scanner myObj = new Scanner(System.in);
        int num1 = 0;
        int num2 = 1;
        int n;
            System.out.println("How many elements would you like in your Fibonacci sequence?");
            n = myObj.nextInt();
                if (n < 0)
                    System.out.println("Positive numbers only!");
                else 
                    System.out.println("Your Fibonacci sequence with " + n + " elements is:");
                    { for (int i = 1; i <= n; ++i)
                        { 
                            System.out.print(num1 + " ");
                            int num3 = num1 + num2;
                            num1 = num2;
                            num2 = num3;
                            ++i;
                        }

                    }
            }
}

I'm struggling to imagine what the problem could be. I first thought it might be a problem with the test condition statement, but similar (working) solutions online seem to have their loops formatted almost identically. Is it perhaps a problem with my variable declarations? I've tried multiple changes to no avail so would appreciate another set of eyes :)

1 Answers

You could just delete the second i++; statement in your code, this one is making the for loop run half times as expected, since the i variable is being incremented twice on each iteration

public class fibonacci_input {

    public static void main(String[] args) {

        Scanner myObj = new Scanner(System.in);
        int num1 = 0;
        int num2 = 1;
        int n;
            System.out.println("How many elements would you like in your Fibonacci sequence?");
            n = myObj.nextInt();
                if (n < 0)
                    System.out.println("Positive numbers only!");
                else 
                    System.out.println("Your Fibonacci sequence with " + n + " elements is:");
                    { for (int i = 1; i <= n; ++i)
                        { 
                            System.out.print(num1 + " ");
                            int num3 = num1 + num2;
                            num1 = num2;
                            num2 = num3;
                            //++i;
                        }

                    }
            }
}
Related