* This is for CS 101 Java class. I can only use \"for\" and “do-while” loops for
ID: 3727776 • Letter: #
Question
* This is for CS 101 Java class. I can only use "for" and “do-while” loops for this lab assignment. I cannot use “while" or any other repetition method. *
Create a new project Lab05d. Write a program that reads an integer n from the user and displays the first n Fibonacci numbers (5 numbers per line, each number right aligned). The fibonacci numbers are defined as follows Sample run: Enter a positive integer: -9 Enter a positive integer: -3 Enter a positive integer: 0 Enter a positive integer: 30 30 Fibonacci numbers are: 21 233 2584 28657 317811 3 34 377 4181 46368 514229 13 144 1597 89 987 10946 121393 610 6765 75025 832040 196418Explanation / Answer
Note: When u run the program u will get the exact output.Thank You
_______________
FibonacciNumbers.java
import java.util.Scanner;
public class FibonacciNumbers {
public static void main(String[] args) {
//Declaring variables
int n;
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner sc = new Scanner(System.in);
do {
//Getting the input entered by the user
System.out.print("Enter a positive number :");
n = sc.nextInt();
} while (n <= 0);
System.out.println(n + " Fibonacci numbers are: ");
for (int i = 1; i <= n; i++) {
System.out.printf("%10d ", fibonacci(i));
if (i % 5 == 0)
System.out.println();
}
}
// This method will generate the fibonacci numbers
public static int fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}
____________________
Output:
Enter a positive number :30
30 Fibonacci numbers are:
1 1 2 3 5
8 13 21 34 55
89 144 233 377 610
987 1597 2584 4181 6765
10946 17711 28657 46368 75025
121393 196418 317811 514229 832040
______________Thank You
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.