programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Recursion

Ranch Hand
Posts: 55
Hi all!
I'm new to this sight and I already love it! I am taking a begginer course in java and I'm asked to write a non-recursive method that computes fibonacci numbers. I sort of understand what fibonacci numbers are but I really don't understand the whole recursion thing. Can anybody explain to me in layman's terms what recussive and non-recurssive methods are?
I would really appreciate it.
Thank you
Stacey

Greenhorn
Posts: 8
Hi Stacey
Recursion is a technique where a method calls itself again an againg until a certain breaking condition occurs. I don't remember the fibronacci formula but here is a small program computing the factorial first with and then without recursion:

If you call the program with 5 as argument, the recursive method will call itself 5 time with one substracted at each recursion. The total sequence is recursiveFactorial(5) * recursiveFactorial(4) * ... * recursiveFactorial(0) (ie: 5*4*3*2*1*1=120 )
Good luck.
Frank

Ranch Hand
Posts: 1170
another point of interest is stack space. One often avoids recursive methods because they can use lots of stack space.
each time a method is invoked it takes up some stack space until that method exits. The recursive method will continue to take more stack space at each new call of the method until the final method is reached and exited.
if you put a BIG number in the recursive method it can throw an StackOverflowException or the like. The non-recursive method will not.

 PI day is 3.14 (march 14th) and is also einstein's birthday. And this is merely a tiny ad: The WEB SERVICES and JAX-RS Course https://coderanch.com/t/690789/WEB-SERVICES-JAX-RS