Computer Science

Write a program that reads the n to display nth term of Fibonacci series.

The Fibonacci sequence works as follows:

  • element 0 has the value 0
  • element 1 has the value 1
  • every element after that has the value of the sum of the two preceding elements

The beginning of the sequence looks like:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

The program prompts for element and prints out the value of that element of the Fibonacci sequence.

Thus:

  • input 7, produces 13
  • input 9, produces 34

Hints:
A Don't try to just type out the entire list. It gets big very fast. Element 25 is 75205. Element 100 is 354224848179261915075. So keep upper limit of n to 20.

Python

Python List Manipulation

15 Likes

Answer

n = int(input("Enter n: "))

if (n > 20):
    print("n should be less than or equal to 20")
else :
    a = 0
    b = 1
    c = a + b
    for i in range(3, n + 1):
        a = b
        b = c
        c = a + b

    print(n, "term of Fibonacci series =", c)

Output

Enter n: 7
7 term of Fibonacci series = 13

=====================================

Enter n: 9
9 term of Fibonacci series = 34

=====================================

Enter n: 25
n should be less than or equal to 20

Answered By

7 Likes


Related Questions