4 Replies - 2171 Views - Last Post: 10 April 2013 - 06:58 AM

Is an increment allowed in a Recursive method?

Posted 09 April 2013 - 04:56 PM

Hey guys I am taking CS 102 and for a project I need to utilize a recursive method to find the area of a polygon using a predefined equations. I will like to know are incrementers like i++ allowed in a recursive method?

Re: Is an increment allowed in a Recursive method?

Posted 10 April 2013 - 02:07 AM

Recursion is just a method that calls itself. You can do whatever you like in that method, including incrementing.

However, recursion is often used instead of looping. There are times when combining recursion and looping is a good idea (e.g. merge sort) but if you are learning about recursion in class, they should be teaching you how to use it as an alternative to looping.

Once you aren't dealing with loops inside the method, there is less reason to change the contents of variables. Instead of x++; you could say int y = x + 1;. You might prefer x++ because it makes things more readable or you might be overly-obsessed about the consequences of allocating 1 extra variable. However convenient it is to modify the variable, it is not necessary.

Re: Is an increment allowed in a Recursive method?

Posted 10 April 2013 - 06:58 AM

Each step of a recursion should be conceptually insulated in its context: it just asks a few questions and returns a result, possibly calling some function to do this. The fact that the function is might call happens to be another iteration of the same function shouldn't make any difference at all: it's just a function that returns a value that you need. This iteration shouldn't affect anything but its own local variables, and no other function should affect the variables local to this function.

The important thing is to know the rules of the language you're using, particularly around scope and how arguments are passed. For example, looking at javascript I'm always a little afraid of the scoping rules, because they are not simple, and it's easy to get yourself in the wrong scope and screw things up. I'd be concerned about using ++ in a recursive function in javascript at least until I have a chance to know that language a lot better than I do now.

Likewise, if you're using Java or python and you pass an object (such as a list) to a function, you're creating an alias, so for example popping an item off the list can cause great confusion.