“The Fibonacci sequence is a series of numbers where a number is found by adding
ID: 3735608 • Letter: #
Question
“The Fibonacci sequence is a series of numbers where a number is found by adding up the two numbers before it. The sequence goes 1, 1, 2, 3, 5, 8, 13, 21, 34, and so forth. Written as a rule, the expression is xn = xn-1 + xn-2.”
We can compute the first 10 numbers in the sequence as follows:
F1 = 1
F2 = 1
F3 = F2 + F1= 1+1 = 2
F4 = F3 + F2= 2+1 = 3
F5 = F4 + F3= 3+2 = 5
F6 = F5 + F4= 5+3 = 8
F7 = F6 + F5= 8+5 = 13
F8 = F7 + F6= 13+8 = 21
F9 = F8 + F7= 21+13 = 34
F10 = F9 + F8 = 34+21 = 55
Write a program that will ask the user how many numbers from the Fibonacci sequence they’d like to see (should work for any value, not just for 10!).
Sample output:
How many values of the Fibonacci sequence would you like to see?
The first 7 values are: 1 1 2 3 5 8 13
writ it in java
Explanation / Answer
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// DECLARING variables
int a = 1, b = 1, n;
Scanner sc = new Scanner(System.in);
// taking user input
System.out.print("How many values of the Fibonacci sequence would you like to see? ");
n = sc.nextInt();
// printing output
System.out.print("The first "+n+" values are: ");
for(int i=0; i<n; i++)
{
// adding two number each time to have next number
System.out.print(a+" ");
int temp = a;
a = b;
b = b+temp;
}
}
}
/*SAMPLE OUTPUT
How many values of the Fibonacci sequence would you like to see? 7
The first 7 values are: 1 1 2 3 5 8 13
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.