-1
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 ?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 1
    To avoid the stack overflowing, you need to implement this function differently. Recursion just won't cut it after a while. – Frontear Nov 28 '21 at 22:32
  • So the recursion if called to many times will eventualy give a stack overflow error ? – Proximo_224 Nov 28 '21 at 22:37
  • 2
    Correct. This is a fundamental problem of recursion that cannot be changed. – Frontear Nov 29 '21 at 04:18
  • 1
    Does this answer your question? [What is a StackOverflowError?](https://stackoverflow.com/questions/214741/what-is-a-stackoverflowerror) – Tomerikoo Nov 29 '21 at 08:11
  • Thank you for the answers. It was a homework for me how to avoid the SO error. Have to solve it with standard for loop. – Proximo_224 Nov 29 '21 at 18:34

1 Answers1

2

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.

Based1776
  • 79
  • 4