what is the difference between recursive and iterative? thanks
recursive is when part of the program is running itself. ex: squareroot(squareroot(squareroot(squareroot(99)))) iterative is running the same program over and over again. ex: squareroot(1) squareroot(2) squareroot(3) squareroot(4)
I had a long exchange with a very helpful member of this group (carlsmith) who very patiently explained recursion to me. Here's a link to that long discussion: http://openstudy.com/groups/mit+6.00+intro+computer+science+%28ocw%29/updates/4e88cecc0b8b543d41e25397#/groups/mit+6.00+intro+computer+science+%28ocw%29/updates/4e6a55580b8b4a2b95d4d5c7 Basically, a recursive function calls itself. An iterative function works through a problem using a list, like x+1 = answer. To find the answer if x is between 1 and 100, the iterative function would test 1, then test 2, then test 3... until it got to 100 and it would stop.
Iteration uses (usually) a loop to repeatedly perform some task. Recursion uses a function that calls itself from within itself to implement the repitition. Here is how the factorial operation would be implemented in the two ways: def iterativeFactorial(n): if n < 2: return 1 product = 1 for i in range(1, n + 1): product *= i return product def recursiveFactorial(n): if n < 2: return 1 return n * recursiveFactorial(n - 1)
Join our real-time social learning platform and learn together with your friends!