Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I couldn't decide if the following function is iterative or recursive,

I think it's recursive because it repeats itself, but since it has a while loop I have doubts,

def function(n):
    while((n!=1) and (n!=0)):
        return function(n-1) + function(n-2)
    return n
share|improve this question
    
It's recursive, because function calls itself. That's the definition of recursion. Also see my comment. –  rantanplan Oct 28 '12 at 1:41

2 Answers 2

up vote 5 down vote accepted

It’s recursive as it calls itself. Recursivity (is that a word) does not mean that there are no “standard” iterations allowed.

And btw. in your case, there are no further iterations. The while loop is essenially identical to a simple if statement, as you immediately return in the first loop. So you could write it like this:

def function(n):
    if (n != 1) and (n != 0):
        return function(n - 1) + function(n - 2)
    return n
share|improve this answer
    
I guessed so, but I couldn't be sure, thanks –  user1110409 Oct 28 '12 at 1:45

A function can have a loop and be recursive. A function is called recursive if it calls itself, but be aware that a function doesn't necessarily need to call itself to be considered recursive, take a look at this example:

def even(n):
    return True if n == 0 else odd(n - 1)

def odd(n):
    return False if n == 0 else even(n - 1)

even(10)
> True
odd(10)
> False

The above functions are "mutually recursive".

share|improve this answer
2  
Well, you would still say that they call themselves—indirectly. –  poke Oct 28 '12 at 1:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.