Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

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;
	}
}
Comment

PREVIOUS NEXT
Code Example
Java :: A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade java.lang.OutOfMemoryError (no error message) 
Java :: java get color from string 
Java :: how to create java jframe in eclipse 
Java :: android parse time 
Java :: gradle build with javadoc 
Java :: ubuntu java compiler version 
Java :: admost track purchase 
Java :: how to set lowered bezels in jlabel 
Java :: Bootstrap 4 Navbar Dropdown Menu Items Right 
Java :: Selection Structure and Conditions 
Java :: stringbuilder java extends object 
Java :: find all possible substrings of a string java 
Java :: how to create listpopupwindow android studio 
Java :: android how to start a new activity on button click 
Java :: filesaver javafx 
Java :: cast double to string java 
Java :: java string lowercase 
Java :: Not supported for DML operations 
Java :: How to efficiently invert a binary tree, in Java? 
Java :: how to use ? in java without using if 
Java :: public static int to String java 
Java :: spring get bean with generic type 
Java :: java only close socket outputstream 
Java :: character.isalphanumeric java 
Java :: java how to get current time 
Java :: show input dialog java 
Java :: fibonacci sequence in java recursion 
Java :: java.lang.NullPointerException: Cannot invoke "java.lang.CharSequence.length()" because "this.text" is null 
Java :: javafx textarea font size 
Java :: how to convert outputstream to bytearrayoutputstream in java 
ADD CONTENT
Topic
Content
Source link
Name
2+4 =