In: Computer Science
PART 1: WRITE A PROGRAM THAT TAKES IN TWO INTEGERS VALUE N AND M (USER INPUT) AND CALCULATES THE NTH FIBONACCI SUM USING RECURSION.
EXAMPLE: OLD VERSION 0,1,1,2,3.. USING USER INPUT: 0, N, M ,N+M, (N+M)+M
PART 2: WRITE THE SAME PROGRAM USING USER INPUT BUT USING A LOOP IN STEAD OF RECURSION.
PYTHON
I have written the program using PYTHON PROGRAMMING LANGUAGE.
USING RECURSION :
OUTPUT :
CODE :
#function definition for Fibonacci
def Fibonacci(N,M,Nthposition):
if(N<=0):
return "InvalidInput" #in case of invalid input
elif(Nthposition-1 == 0):
print(N,end=" ")
return N
else:
print(N,end=" ")
#calling Fibonacci function recursively
return Fibonacci(M,N+M,Nthposition-1)
if(__name__ == "__main__"):
#taking user input for N and M values
N = int(input("Enter an integer value for N : \t"))
M = int(input("Enter an integer value for M : \t"))
print("\nFibonacci Series \n0",end=" ")
#calling Fibonacci function
result = Fibonacci(N,M,N)
#To validate the result and printing the reuslt on the console
if(result == "InvalidInput"):
print("Invalid Input !!!")
else:
print("\n\nOUTPUT : \n{:d}th Fibonacci SUM is {:d}".format(N,result))
USING LOOP :
OUTPUT :
CODE :
if(__name__ == "__main__"):
#taking user input for N and M values
N = int(input("Enter an integer value for N : \t"))
M = int(input("Enter an integer value for M : \t"))
#calling Fibonacci function
NOriginal = N
Nthposition = N
#in case if N value is negative or 0
if(N<=0):
print("Invalid Input !!!")
else:
print("\nFibonacci Series \n0",end=" ")
#while loop to calculate the fibnocci
Series
while(Nthposition - 1 !=0):
print(N,end=" ")
N , M = M , N+M
Nthposition -= 1#decreasing the
Nthposition by value 1
print(N,end=" ")
#to print the result on the console
print("\n\nOUTPUT : \n{:d}th Fibonacci SUM is
{:d}".format(NOriginal,N))
Thanks..