Could someone explain recursion to me please. I get that a function loops coz it is called several times but I can't get why and how! Frustration.
Welcome to the Java Programming Forums
The professional, friendly Java community. 21,500 members and growing!
The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.
>> REGISTER NOW TO START POSTING
Members have full access to the forums. Advertisements are removed for registered users.
Could someone explain recursion to me please. I get that a function loops coz it is called several times but I can't get why and how! Frustration.
You are probably missing an exit condition. Show the codes you have.
In a nutshell:
if condition is met return else call function again
Thread moved from "Whats wrong with my code?"
Recursion simply means recurring again and again. In another word, it is function calling the function itself until certain condition is met. For example:- If you look at the Fibonacci number(fibonacci number is sequence of number where the next number is the addition of past two numbers). The fibonacci numbers are 0,0,1,1, 2, 3, 5, 8. 8 is obtained by adding 5 and 3, 5 is obtained by adding 2 and 3 and so on. This can be generated easily by recursion.
Anything that can be done with recursion can also be done iteratively or without using recursion. When you use recursion it keeps your code short. However, in java it is advisable not to use recursion because of the performance and memory issue. But it doesn't mean recursion is bad. In other programming language like LISP, recursion is the best way of solving problems. Don't bother too much about it. Just learn its basics and how it works. You will hardly use recursion in future if you continue in java.
kevthanewversi (April 21st, 2013)
Each call to the method is the same as any other call to any other method.
If you don't understand my answer, don't ignore it, ask a question.