Monday, April 3, 2023

Program to generate Fibonacci series in Python

# Program to generate Fibonacci series in Python

# Prompt the user to enter the number of terms

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

# Initialize the first two terms of the series

a = 0

b = 1

# Check if the number of terms is valid

if n <= 0:

   print("Invalid input! Please enter a positive integer.")

elif n == 1:

   print("Fibonacci series up to", n, "term:")

   print(a)

else:

   # Print the series up to the n-th term

   print("Fibonacci series up to", n, "terms:")

   print(a, b, end=" ")

   for i in range(2, n):

       c = a + b

       print(c, end=" ")

       a = b

       b = c

Output:

Fibonacci series up to 5 terms:

0 1 1 2 3

This means that the program has generated the first 5 terms of the Fibonacci series, which are 0, 1, 1, 2, and 3.

In this program, we prompt the user to enter the number of terms they want in the Fibonacci series. We then initialize the first two terms of the series to be 0 and 1. We check if the number of terms entered by the user is valid or not. If it is less than or equal to zero, we print an error message. If it is equal to one, we print the first term of the series. Otherwise, we use a loop to generate and print the series up to the n-th term.

 

In the loop, we calculate the next term of the series by adding the previous two terms. We print each term of the series as we generate it. Finally, we update the values of a and b to prepare for the next iteration of the loop.

No comments:

Post a Comment

Apeejay Surrendra Park Hotels IPO: Should You Invest Today?

The Apeejay Surrendra Park Hotels (ASPH) IPO hits the market today, February 5th, 2024, offering a chance to invest in a well-established...