153k views
4 votes
The Fibonacci numbers are defined by the series 0, 1, 1, 2, 3, 5, 8 ,13, ... Write a program that implements the Fibonacci series. Implement a program that prompts the user for an integer n and prints the nth Fibonacci number, using the following algorithm. First, Take care of negative numbers that are not defined by this series by printing an appropriate message. Next, take care of the initial conditions: fib1 = 1 fib2 = 1 fnew = fib1 + fib2 After that, compute an updated value of fnew, fib1, and fib2, per loop iteration. Repeat an appropriate number of times. Using loop only, without functions

User Zlinks
by
8.7k points

1 Answer

5 votes

Final answer:

To implement the Fibonacci series using a loop, prompt the user for an integer and calculate each number in the series based on the position. Handle negative numbers appropriately and use a for loop to update the values until the desired Fibonacci number is reached.

Step-by-step explanation:

To implement the Fibonacci series, you can use a loop to calculate each number in the series. Start by prompting the user for an integer 'n' to determine the position of the desired Fibonacci number. If 'n' is negative, print an appropriate message. Otherwise, initialize 'fib1' and 'fib2' as 0 and 1, respectively. Use a for loop to iterate 'n' times, updating 'fib1' and 'fib2' on each iteration by setting 'fib1' to the current value of 'fib2', and 'fib2' to the sum of the current values of 'fib1' and 'fib2'. After the loop ends, 'fib2' will contain the desired nth Fibonacci number, which you can print to the console.

User Kishore Indraganti
by
8.8k points