Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

How to code the Fibonacci Sequence using simple iterative loops in java

// Here's how to get the nth Fibonacci number code in Java using a while loop:

import java.util.*;
public class fibonacci{
    public static void main(String args[]){
        int n,k;
        Scanner snr= new Scanner(System.in);
        n=snr.nextInt();
        snr.close();
        int array[]=new int[n];
        // The space used here is O(N)
        array[0]=0;
        array[1]=1;
        k=2;
        while(k<n)
            array[k]=array[k-1]+array[k-2];
            k++;
        System.out.println("Nth number in Fibonacci series is "+array[n-1]);
    }
    // The array is traversed only once so the time complexity is O(N)
}
Source by www.freecodecamp.org #
 
PREVIOUS NEXT
Tagged: #How #code #Fibonacci #Sequence #simple #iterative #loops #java
ADD COMMENT
Topic
Name
3+5 =