-3

I am wondering when use the recursion and iterative method please tell me which approch best and why ? I don't know about the Data structure and Algorithm.

This is Recursive approach.

def recurse(n):
  print(n)
  if n==0:
    return 0  
  return recurse(n-1)
recurse(10)
print(recurse(10))

This is Itrative approach.

def factorial(n):
    if n < 0:
        return 0
    elif n == 0 or n == 1:
        return 1
    else:
        fact = 1
        while(n > 1):
            fact *= n
            n -= 1
        return fact

print(factorial(5))
Evg
  • 25,259
  • 5
  • 41
  • 83

1 Answers1

1

Like LinFelix in the comments said. "Which is better" is a broad question. I have here somesources you can read up on to better understand which is better in your case: