java.lang.StackOverflowError due to recursion

前端 未结 10 2284
南方客
南方客 2020-12-03 05:59

My problem is that I usually get a java.lang.StackOverflowError when I use recursion. My question is - why does recursion cause stackoverflow so much more than loops do, and

10条回答
  •  余生分开走
    2020-12-03 06:46

    Here for loop is used inside the recursive function. When the recursive function is called, for(int i=0; i the value of i is initialized to zero, as it calls itself, the value of i will again be initialized to zero and it conitues infintely. This will lead you to Stack overflow error.

    Solution: Avoid for loop inside recursive function; instead go for while or do-while and initialize the value of i outside recursive function

提交回复
热议问题