Java

for

public class Program {
public static int **fibonacci**(int n) {
int a = 0;
int b = 1;
*// Compute Fibonacci sequence.*
for (int i = 0; i < n; i++) {
int temp = a;
a = b;
b = temp + b;
}
return a;
}
public static void main(String[] args) {
*// Get first 15 Fibonacci numbers.*
for (int i = 0; i < 15; i++) {
System.out.println(fibonacci(i));
}
}
}0
1
1
2
3
5
8
13
21
34
55
89
144
233
377

Array

public class Program {
public static int[] **fibonacci**(int n) {
int a = 0;
int b = 1;
int[] sequence = new int[n];
*// Fill array with Fibonacci values.*
for (int i = 0; i < n; i++) {
sequence[i] = a;
int temp = a;
a = b;
b = temp + b;
}
return sequence;
}
public static void main(String[] args) {
*// Get Fibonacci array.*
int[] sequence = fibonacci(15);
for (int value : sequence) {
System.out.println(value);
}
}
}0
1
1
2
3
5
8
13
21
34
55
89
144
233
377

Recursion

Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.

Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.

No updates found for this page.