Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

How to code the Fibonacci Sequence using simple iterative loops java

// Here's how to get the nth Fibonacci number Code in Java using a for 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;
        for(k=2;k<n;k++)array[k]=array[k-1]+array[k-2];
        // The array is traversed only once so time complexity is O(N)
        System.out.println("Nth number in Fibonacci series is "+array[n-1]);
    }
}
Source by www.freecodecamp.org #
 
PREVIOUS NEXT
Tagged: #How #code #Fibonacci #Sequence #simple #iterative #loops #java
ADD COMMENT
Topic
Name
4+9 =