Computer Assignment4
Computer Assignment4
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:
previous two numbers are added to get the immediate new number.
ANSWER:
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: