Problem statement: How do you print Fibonacci series?
Def: A series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers.
Method-II:
Def: A series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers.
- public class FibonacciSeries {
- public static void main(String[] args) {
- int count = 10;
- printFibonacci(count);
- }
- public static void printFibonacci(int count) {
- int a = 0, b = 1, c = 0;
- System.out.print(a + " " + b + " ");
- for (int i = 2; i < count; i++) {
- c = a + b;
- a = b;
- b = c;
- System.out.print(c + " ");
- }
- }
- }
Output:
0 1 1 2 3 5 8 13 21 34
Method-II:
- public class FibonacciSeries {
- public static void main(String[] args) {
- fibonacci(10); // 10 is count
- }
- public static void fibonacci(int n) {
- int a[] = new int[n];
- a[0] = 0;
- a[1] = 1;
- System.out.print(a[0] + " " + a[1] + " ");
- for (int i = 2; i < n; i++) {
- a[i] = a[i - 1] + a[i - 2];
- System.out.print(a[i] + " ");
- }
- }
- }
Output:
0 1 1 2 3 5 8 13 21 34
No comments:
Post a Comment