Answers for "How to find the fibonacci of an integer value iteratively in Java?"

1

How to find the fibonacci of an integer value iteratively in Java?

public class Fibonacci {
	/*
	 * Fibonacci sequence starts with 0 and 1, then
	 * any subsequent value is sum of 2 previous ones.
	 * 0, 1, 1, 2, 3, 5, 8, etc...
	 * fib(0) = 0 and fib(1) = 1
	 * fib(n) = fib(n-1) + fib(n-2)
	 */
	public static void main(String[] args) {
		System.out.println(fib(3)); // 2
		System.out.println(fib(6)); // 8
	}

	// Supporting method for finding fib at n
	private static int fib(int n) {
		int prevprev = 0, prev = 1;
		int current = n;
		// Loop until reaching n each time
		// deriving current based on 2
		// previous values
		for (int i = 2; i <= n; i++) {
			current = prevprev + prev;
			prevprev = prev;
			prev = current;
		}
		return current;
	}
}
Posted by: Guest on April-27-2022
2

fibonacci in java

// Java program for the above approach
  // divyaraj
class GFG {
  
    // Function to print N Fibonacci Number
    static void Fibonacci(int N)
    {
        int num1 = 0, num2 = 1;
  
        int counter = 0;
  
        // Iterate till counter is N
        while (counter < N) {
  
            // Print the number
            System.out.print(num1 + " ");
  
            // Swap
            int num3 = num2 + num1;
            num1 = num2;
            num2 = num3;
            counter = counter + 1;
        }
    }
  
    // Driver Code
    public static void main(String args[])
    {
        // Given Number N
        int N = 10;
  
        // Function Call
        Fibonacci(N);
    }
}
Posted by: Guest on January-26-2022

Code answers related to "How to find the fibonacci of an integer value iteratively in Java?"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language