+ 1
Can you help me understand how recursive methods work?
I am currently learning Java and I am introducing myself to recursive methods and the truth is that I still cannot understand it. I have searched on AI and YouTube but I cannot understand and I would like to Someone help me, I would really appreciate it. Although I think the SoloLearn community is dead, I know someone will see this and help me. Thanks 🫂
3 Réponses
+ 5
Enrique Sanchez ,
i have put some basic explanations (+ simple java code snippet) about recursion in the attached file.
https://sololearn.com/compiler-playground/chheOG8ZrUYA/?ref=app
+ 3
What are you having trouble understanding?
It's a method which calls itself... think of it as a kind of loop.
Maybe searching here or the code playground for examples might help to see what people do with it. You should then try to code one and maybe that will help with your understanding.
https://sololearn.com/compiler-playground/cUV6Cch8652z/?ref=app
https://sololearn.com/compiler-playground/c5A8aioWW4fZ/?ref=app
https://sololearn.com/compiler-playground/cSyu4aFdd9il/?ref=app
https://sololearn.com/compiler-playground/cMN9i2JKwZSG/?ref=app
+ 2
Imagine calling the function "calculator", and sending it 2+(2+2). It can't just evaluate left to right or it'll be wrong. A simple workaround would be having the function call itself when the argument is anything but "number operator number". In the example it would discover "2+" and store that, then discover the parenthesized "(2+2)" and call itself with that (removing parentheses to prevent an endless loop, which would cause a fatal error). That returns 4 to the original call, which finally gets evaluated as "2+4" and returns the final result. Maybe oversimplified, but that's the gist of it - a function that somehow discovers nested values and uses itself to evaluate/simplify them or perform some action on them, possibly gathering them into a more friendly blob or simplified result.