The Question:
A Fibonacci sequence is the sequence of numbers 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on, where each number (from the third on) is the sum of the previous two. Create a method that takes an integer as an argument and displays that many Fibonacci numbers starting from the beginning, e.g., If you run java Fibonacci 5 (where Fibonacci is the name of the class) the output will be: 1, 1, 2, 3, 5.
My Answer:
public class Fibonacci {
/**
* @param args
*/
static void f(int i){
if (i < 2)
System.out.println("The number you entered must be bigger than 1");
else{
int a[] = new int[i];
for(int j = 0;j < i;j++) {
a[0] =a[1] = 1;
if(j >= 2){
a[j] = a[j-1] +a[j-2];
}
System.out.print(a[j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Fibonacci.f(9);
Fibonacci.f(7);
Fibonacci.f(4);
}
}
A Fibonacci sequence is the sequence of numbers 1, 1, 2, 3, 5, 8, 13, 21, 34, and so on, where each number (from the third on) is the sum of the previous two. Create a method that takes an integer as an argument and displays that many Fibonacci numbers starting from the beginning, e.g., If you run java Fibonacci 5 (where Fibonacci is the name of the class) the output will be: 1, 1, 2, 3, 5.
My Answer:
public class Fibonacci {
/**
* @param args
*/
static void f(int i){
if (i < 2)
System.out.println("The number you entered must be bigger than 1");
else{
int a[] = new int[i];
for(int j = 0;j < i;j++) {
a[0] =a[1] = 1;
if(j >= 2){
a[j] = a[j-1] +a[j-2];
}
System.out.print(a[j] + " ");
}
System.out.println();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Fibonacci.f(9);
Fibonacci.f(7);
Fibonacci.f(4);
}
}