Here is an example of a recursive program:
def f(i):
if i > 0:
return f(i-1) + i
else:
return 0
This program will return the sum of the sequence of i to 0 such as i = 5 so 5+4+3+2+1 = 15. Otherwise, this program will return 0 (anything <= 0). This can be done through other methods, but it is simpler and more efficient with recursion.
Now for my above explanation I apologize, it may be confusing for two reasons.
1. Recursion can be a very confusing concept and,
2. I am very bad at explaining things.
Everyone in class is at the point where they are able to trace recursion somewhat easily, but the hard part is to visualize it for a problem presented before them is still hard. Granted I am still trying to make this process easy through practice and just from seeing other recursive solutions. Recursion will be one of the best things you can find to do many hard things, easier! The Fibonacci sequence is one of the problems you can easily figure out using recursion. It makes programming way easier than hard coding it. It would take forever to be able to hard code the Fibonacci sequence using only for loops. Its a good thing you know recursion because (photo):
No comments:
Post a Comment