मराठी

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

प्रश्न

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.

थोडक्यात उत्तर
Advertisements

उत्तर

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
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 7: Functions - Exercise [पृष्ठ १७२]

APPEARS IN

एनसीईआरटी Computer Science [English] Class 11
पाठ 7 Functions
Exercise | Q 4. | पृष्ठ १७२
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×