fibonacci sequence without recursion

Solutions on MaxInterview for fibonacci sequence without recursion by the best coders in the world

showing results for - "fibonacci sequence without recursion"
Felix
09 Jun 2019
1int fibonacci(int i, int sum1, int sum2) 
2{
3    if(i == 1) {
4        return sum2;
5    }
6    return fibonacci(i - 1, sum2, sum1 + sum2);
7}
Fatima
24 Mar 2019
1import java.util.ArrayList;
2import java.util.HashMap;
3import java.util.Map;
4
5
6/**
7 * Java Program to print Fibonacci series without using recursion.
8 * input : 10
9 * output : 0 1 1 2 3 5 8 13 21 34 55 
10 *
11 * @author WINDOWS 8
12 */
13
14public class FibonacciSeriesWithoutRecursion {
15
16    public static void main(String args[]) {
17     
18        // printing first 10 numbers of Fibonacci series
19        fibonacci(10);
20     
21    }
22     
23 
24    public static void fibonacci(int number){
25        for(int i=0; i <= number; i++){
26            System.out.print(getFibonacci(i) + " ");
27        }
28    }
29  
30    /**
31     * This function return nth Fibonacci number in Java
32     * @param n
33     * @return nth number in Fibonacci series
34     */
35    public static int getFibonacci(int n){
36      
37        if (n == 0) {
38            return 0;
39        }
40        
41        if (n == 1){
42            return 1;
43        }
44
45        int first = 0;
46        int second = 1;
47        int nth = 1;
48
49        for (int i = 2; i <= n; i++) {
50            nth = first + second;
51            first = second;
52            second = nth;
53        }
54        return nth;
55    }
56  
57}
58
59Output : 0 1 1 2 3 5 8 13 21 34 55