Find nth Fibonacci number Algorithm in Java with a PRACTICAL EXAMPLE using while loop
Coding River
Find nth Fibonacci number Algorithm in Java with a PRACTICAL EXAMPLE using while loop
In this video, we are going to write a program that uses a while loop to find a Fibonacci number by specifying its position in the Fibonacci sequence In Mathematics, Fibonacci numbers form a sequence of numbers called the Fibonacci sequence By definition, the Fibonacci sequence is a series of numbers where each number is the addition of the last two preceding numbers starting with 0 and 1
Here on the screen is an example of that sequence
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ....
In this sequence, for example, you can notice that 34 is the result of the addition between the preceding numbers which are 21 and 13 Or 21 is the result of the addition between 13 and 8 13 is the result of the addition between 5 and 8 8 is the result of the addition between 3 and 5
From the sequence on the screen You can determine the next Fibonacci number by applying the same logic Which is to add up 21 and 34 in order to get 55
As I said at the beginning, in this video we are going to develop a program that will allow us to find the Fibonacci number that occupies a specific position in the sequence
The program must allow the user to input the position of the desired Fibonacci number in the Fibonacci sequence
That simply means that we need to get the first two Fibonacci numbers, the position of the desired number in the Fibonacci sequence Then calculate the next Fibonacci number by adding the previous two elements of the Fibonacci sequence And repeat this step until the desired Fibonacci number is found Then print out that Fibonacci number
Here is how the code will look like
First, let’s declare the input object like this Static Scanner console = new Scanner(System.in)
Second, let’s declare the various variables used in the program The first variables will be the ones to store the first two numbers of the Fibonacci sequence int number1 = 0 Int number2 = 1;
The next variable will be the one that stores the desired Fibonacci number int fibonacci_number;
I will need another variable that will store the position of the Fibonacci number we are looking for int number_position;
Then, the other variable will be the loop control variable int counter;
Now, let’s write the output statements The first output statement will tell the user about the first and second Fibonacci number of the sequence System.out.println(“The first two numbers of the Fibonacci sequence are “ + number1 + “ and “ + number2); The second statement will prompt the user to enter the position of the desired Fibonacci number System.out.println(Please enter the position of the Fibonacci number you desire to see);
Right after that, let’s add an input statement to allow the user to enter the position number_ ... https://www.youtube.com/watch?v=TjPM7NeF51E
19917291 Bytes