Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Tuesday, April 16, 2024

Program in python to generate first n Fibonacci terms using recursive function.

 Code:

def fibonacci_recursive(n):

    # Base case: return 0 for the first term

    if n == 0:

        return 0

    # Base case: return 1 for the second term

    elif n == 1:

        return 1

    else:

        # Recursive case: F(n) = F(n-1) + F(n-2)

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

# Example usage

try:

    n = int(input("Enter the number of Fibonacci terms to generate: "))

    if n < 0:

        raise ValueError("Please enter a non-negative integer.")

    fibonacci_sequence = [fibonacci_recursive(i) for i in range(n)]

    print(f"The first {n} Fibonacci terms are: {fibonacci_sequence}")

except ValueError as e:

    print(f"Error: {e}")


Output:





No comments:

Post a Comment