English

Take a look at the series below: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55… To form the pattern, start by writing 1 and 1. Add them together to get 2. Add the last two numbers: 1+2 = 3. - Computer Science (Python)

Advertisements
Advertisements

Question

Take a look at the series below:

1, 1, 2, 3, 5, 8, 13, 21, 34, 55… To form the pattern, start by writing 1 and 1. Add them together to get 2. Add the last two numbers: 1 + 2 = 3. Continue adding the previous two numbers to find the next number in the series. These numbers make up the famed Fibonacci sequence: the previous two numbers are added to get the immediate new number.

Answer in Brief
Advertisements

Solution

The number of terms of the Fibonacci series can be returned using the program by getting input from the user about the number of terms to be displayed.

The first two terms will be printed as 1 and 1 and then using the ‘for’ loop (n - 2) times, the rest of the values will be printed.
Here, ‘fib’ is the user-defined function that will print the next term by adding the two terms passed to it, and then it will return the current term and the previous term. The return values are assigned to the variables such that the next two values are now the input terms.

Program:
def fib(x, y):
    z = x + y
    print(z, end=",")
    return y, z

n = int(input("How many numbers in the Fibonacci series do you want to display? "))

x = 1
y = 1

if(n <= 0):
    print("Please enter positive numbers only")
elif (n == 1):
    print("Fibonacci series up to",n,"terms:")
    print(x)
else:
    print("Fibonacci series up to",n,"terms:")
    print(x, end =",")
    print(y, end =",")
    for a in range(0, n - 2):
        x,y = fib(x, y)
    print()

​OUTPUT:
How many numbers in the Fibonacci series do you want to display? 5
Fibonacci series up to 5 terms:
1,1,2,3,5,
shaalaa.com
  Is there an error in this question or solution?
Chapter 7: Functions - Exercise [Page 172]

APPEARS IN

NCERT Computer Science [English] Class 11
Chapter 7 Functions
Exercise | Q 4. | Page 172
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×