Write a program to find and print a Fibonacci sequence of numbers. The Fibonacci
ID: 3681012 • Letter: W
Question
Write a program to find and print a Fibonacci sequence of numbers. The Fibonacci sequence is defined as follows:
Fn= Fn-2+Fn-1, where F0=0 and F1=1.
Your program should prompt the user to enter a limit, print the sequence up to the limit, and then indicate the greatest power of 2 that the final number printed is divisible by. Assume user input will be between 1 and 4096.
Here is what the user will see when the program is executed:
-----------------------------------
This program prints the Fibonacci sequence
Enter a limit on the largest number to be displayed: 50 50 is Input
1 1 2 3 5 8 13 21 34
The last number 34 is divisible by 2.
Do you want to print a different sequence (Y/N): y y is Input
Enter a limit on the largest number to be displayed: 200 200 is Input
1 1 2 3 5 8 13 21 34 55 89 144
The last number 144 is divisible by 16.
Do you want to print a different sequence (Y/N): n n is Input
Goodbye.
Notes:
1. Make sure to declare word elements before declaring bytes or strings.
2. After using the scanf function, you can then use either the ld or ldub commands to access the input values. The command ld is for the word size elements and ldub is for the byte size elements.
Explanation / Answer
Hi,below is code
CODE:
import java.util.Scanner;
//class for fibonacci series
public class fib_coSeries {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter the value of n: ");
int n = s.nextInt();
fib_co(n);
}
//fibnacci driver method.
public static void fib_co(int n) {
if (n == 0) {
System.out.println("0");
} else if (n == 1) {
System.out.println("0 1");
} else {
System.out.print("0 1 ");
int a = 0;
int b = 1;
for (int i = 1; i < n; i++) {
int nextNumber = a + b;
System.out.print(nextNumber + " ");
a = b;
b = nextNumber;
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.