Python Program for N-Th Fibonacci Number

1. Introduction

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. Fibonacci numbers are a fascinating subject in mathematics and computer science because of their frequency in nature, their applicability in various algorithms, and their occurrence in complex problem-solving scenarios. This blog post will guide you through writing a Python program to find the n-th Fibonacci number, utilizing a simple and efficient approach.

2. Program Steps

1. Prompt the user to enter the value of n for which the n-th Fibonacci number is required.

2. Initialize the first two Fibonacci numbers (0 and 1) and use a loop to generate the subsequent numbers up to n.

3. In each iteration of the loop, update the values of the two most recent Fibonacci numbers and calculate the next number in the sequence.

4. Continue this process until the n-th Fibonacci number is found.

5. Display the n-th Fibonacci number to the user.

3. Code Program

# Step 1: Prompt the user for the value of n
n = int(input("Enter the value of n: "))

# Step 2: Initialize the first two Fibonacci numbers
a, b = 0, 1

# Use a loop to find the n-th Fibonacci number
for i in range(2, n):
    # Step 3: Calculate the next Fibonacci number
    a, b = b, a + b

# Step 4: Check if n is less than or equal to 1 to handle the first two numbers
if n <= 0:
    print("Please enter a positive integer.")
elif n == 1:
    print("The 1st Fibonacci number is 0.")
else:
    # Step 5: Display the n-th Fibonacci number
    print(f"The {n}-th Fibonacci number is: {b}")

Output:

Enter the value of n: 10
The 10-th Fibonacci number is: 34

Explanation:

1. The program starts by asking the user to input the term n in the Fibonacci sequence they wish to find.

2. It initializes the first two numbers of the Fibonacci sequence, 0 and 1, using two variables a and b.

3. Using a loop, it updates these variables to progress through the Fibonacci sequence. In each iteration, a takes the value of b, and b takes the value of a + b, effectively moving forward two steps in the sequence.

4. The program also includes a check for the cases where n is 0 or 1, as these cases are the base conditions of the Fibonacci sequence and need to be handled separately.

5. After completing the loop or identifying the base condition, the program prints the n-th Fibonacci number. This approach is efficient for calculating Fibonacci numbers without requiring recursion, making it suitable for large values of n.


Comments