Search code examples
javarecursionstack-overflow

How to solve a stack overflow error in recursive call?


import java.util.Scanner;

public class Task5 {

    private static void stack(int x) {
        if (x == 0) return;
        stack(x - 1);
        if (x % 35 == 0) {
            System.out.println();
        }
        System.out.print(x + " ");
    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number: ");
        int x = sc.nextInt();
        stack(x);
    }
}

Any number above 9200 results in a stack overflow error. Is it because a recursive call loops too many times ?


Solution

  • Yes, you're encountering an overflow because your recursion stack becomes extremely deep with large inputs. There's no reason this function needs to be recursive, I would suggest implementing an iterative version using loops.