Python Program to Find Fibonacci Series

1. Introduction

The Fibonacci series is a famous sequence in mathematics where each number is the sum of the two preceding ones. Typically, this series is introduced as an example of a recursive algorithm. However, recursion is not always the most efficient approach, especially for large numbers, due to the function call overhead and the potential for stack overflow. Therefore, it is beneficial to implement the Fibonacci series without recursion.

What is the Fibonacci series?

The Fibonacci series is a sequence where each number is the sum of the two preceding ones, usually starting with 0 and 1. That is, F(n) = F(n-1) + F(n-2) with initial values F(0) = 0 and F(1) = 1.

2. Program Steps

1. Initialize the first two numbers of the Fibonacci sequence.

2. Use a loop to iterate and calculate the rest of the numbers in the series up to n.

3. Print each Fibonacci number during the iteration.

4. Store or output the series in the desired format.

3. Code Program

# Function to generate and print the Fibonacci series up to n terms
def fibonacci_series(n):
    a, b = 0, 1
    for _ in range(n):
        # Print the current Fibonacci number
        print(a, end=' ')
        # Update the values of a and b
        a, b = b, a + b
    # Print a new line at the end of the series
    print()

# Number of terms in the Fibonacci series
num_terms = 10
# Generate and print the Fibonacci series
fibonacci_series(num_terms)

Output:

0 1 1 2 3 5 8 13 21 34

Explanation:

1. The function fibonacci_series is defined to generate the Fibonacci series up to n terms.

2. It starts with two integers a and b representing the first two numbers in the Fibonacci series.

3. A loop runs n times using range(n) where _ is the loop variable, indicating that it is not used within the loop.

4. In each iteration, the current Fibonacci number a is printed.

5. Then, a and b are updated to the next two numbers in the series. The new value of a is the old value of b, and the new value of b is the sum of the old a and b.

6. Once the loop completes, it has printed the first num_terms of the Fibonacci series.

7. The output displays the first 10 numbers in the Fibonacci series, separated by spaces.

Comments