-1

I was executing this code and also getting the output but along side that I am also getting a exception message i.e.

Output:

0 1  1 2 3 5 8Exception in thread "main" java.lang.StackOverflowError

and after that more than 100s of line telling at com.company.Main.fibnacci(Main.java:24) with exit code 1

package com.company;
import java.util.Scanner;

class Main {
    static int a = 0;
    static int b = 1;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter no. of terms in fibonacci series ");
        int n = sc.nextInt();
        System.out.print("0 1 ");
        fibnacci(n);
    }

    public static void fibnacci(int n) throws StackOverflowError {
        int c = a + b;
        if (n >= 1) {
            System.out.print(" " + c);
        }
        a = b;
        b = c;
        fibnacci(n - 1);
    }
}
ernest_k
  • 42,928
  • 5
  • 50
  • 93
Rishi Raj
  • 41
  • 8
  • 3
    Does this answer your question? [What actually causes a Stack Overflow error?](https://stackoverflow.com/questions/22182669/what-actually-causes-a-stack-overflow-error) and linked duplicate – jhamon Jan 14 '20 at 10:05
  • 2
    Your code prints if `n >=1`, but it doesn't exit otherwise. You probably need to add `else{return;}`. Your recursion needs a point/condition where it ends. – ernest_k Jan 14 '20 at 10:07

1 Answers1

1

Its because you have to put condition to stop the recursion. This code will keep running because your method will always be called. You need to put one condition to stop calling the method "fibnacci(n - 1)" again once you get your result.

Muhammad bux
  • 61
  • 1
  • 6