Advertisement

Fibonacci series error

Started by April 13, 2023 10:27 AM
5 comments, last by sasha_brouse 1 year, 8 months ago

I'm attempting to print the Fibonacci series using this application. I used n=8 (the number of Fibonacci numbers to print), and I received more than ten. Could you just point out where I'm going wrong?

import java.util.*;
class myprogram{
    static int f=0,s=1,sum=0;
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        System.out.printf("Enter the number of numbers you want to print");
        int n=sc.nextInt();
        System.out.print(f+" "+s);
        fib((n-2));
    }
    static void fib(int count){
        while(count!=0)
        {
            sum=f+s;
            System.out.print(" "+sum);
            f=s;
            s=sum;
            count-=1;
            fib(count);
        }

    }
}

Input:

n=8

Output expected:

0 1 1 2 3 5 8 13 21 33

My result:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6763 10946 17711 28657 46368 75025 121393 ...

I'm going to go out on a limb and say fib(count); is the culprit. You've set up fib to perform the sequence iteratively, but you're also calling it recursively, and since count is passed to each recursive call separately you're calling it something like… 2 + 6 + 5 + 4 + 3 + 2 + 1 times (instead of 2 + 6), I think?

None

Advertisement

As you cannot see what's wrong clearly length 8 is too complicated.

Start with smaller numbers to the point where you can understand why and how it is wrong. Then fix it.

To follow up on Alberth's suggestion, another good way to solve these kinds of issues is to actually use a debugger (no doubt your IDE has one) to follow the flow of the program and see what's actually happening at each step. A lot of novices shy away from debuggers but they're one of the most powerful tools you have at your disposal when it comes to understanding what's happening in your code.

I think had you done that the issue would been pretty clear, and you could've caught it easily without help!

None

How about trying (count<=0) instead of (count!=0) just to see if it is a runoff issue?

Thank you everyone for your help and time

This topic is closed to new replies.

Advertisement