Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Write a program that reads a number n and prints on the console the first n members
- * of the Fibonacci sequence (at a single line, separated by spaces) :
- * 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ….
- * Note that you may need to learn how to use loops. */
- import java.util.Scanner;
- public class FibonacciNumbers {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner scan = new Scanner(System.in);
- System.out.print("Enter a positive number for N: ");
- int numN = scan.nextInt();
- scan.close();
- if (numN >= 1) {
- long fib1 = 0;
- System.out.printf("The first %d members of the Fibonacci sequence are:\n", numN);
- System.out.print(fib1);
- if (numN > 1) {
- long fib2 = 1;
- System.out.print(" " + fib2);
- for (int i = 3; i <= numN; i++) {
- long fibN = fib2 + fib1;
- System.out.print(" " + fibN);
- fib1 = fib2;
- fib2 = fibN;
- }
- }
- } else {
- System.out.println("Error! - Your Number is Out of Range!!!");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement