Question #3371

Write a Fibonacci program in python using recursive function and looping method.

Expert's answer

def fibonacci_recursive (n):

if n == 0: return 0

elif n == 1: return 1

return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)

def fibonacci_iterative (n):

if n == 0: return 0

elif n == 1: return 1

prelast, last = 0, 1

for i in range(n-1):

& new = prelast + last

& prelast, last = last, new

return new

print(fibonacci_recursive(7))

print(fibonacci_iterative(7))

if n == 0: return 0

elif n == 1: return 1

return fibonacci_recursive(n-1) + fibonacci_recursive(n-2)

def fibonacci_iterative (n):

if n == 0: return 0

elif n == 1: return 1

prelast, last = 0, 1

for i in range(n-1):

& new = prelast + last

& prelast, last = last, new

return new

print(fibonacci_recursive(7))

print(fibonacci_iterative(7))

## Comments

## Leave a comment