Skip to content
Advertisement

Fibonacci’s Sequence using forloop

I’m trying to create an array with length n (user input), and I thought that I could use the associated i values within the array to calculate my fibonacci sum.

Here is what I have so far, and I can’t figure out how I should be extracting the i value as an int to be able to calculate the sum.

public class Fibonacci {
    public static void main(String[] args){
        System.out.println("Please enter a value for n: ");
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
    
        int[] newArray = new int[n];
    
        int f1 = newArray[0];
        int f2 = newArray[1];
        
        int i;
        for(i = 1; i <= n; ++i) {
            System.out.print(f1 + " ");
            int sum = f1 + f2;
            f1 = f2;
            f2 = sum;
        }
    }
}

If anyone has any suggestions on how to approach this and can explain a bit of the theory that would be greatly appreciated.

Advertisement

Answer

If you are using an array to store the Fibonacci sequence, you should access the Fibonacci numbers using index in this array and there is no need to use intermediate variables f1, f2, sum.

int[] fiboNums = new int[n]; // assuming n >= 2
    
fiboNums[0] = 1;
fiboNums[1] = 1;

System.out.printf("f(%2d)=%,13d  ", i, fiboNums[i]);        
for (int i = 2; i < n; i++) {
    fiboNums[i] = fiboNums[i - 1] + fiboNums[i - 2];

    System.out.printf("f(%2d)=%,13d  ", i, fiboNums[i]);
    if (i % 5 == 0) {
        System.out.println();
    }
}

However, using int to represent Fibonacci number may not be a good idea because this sequence grows exponentially and integer overflow occurs when i == 46.

f( 1)=            1  f( 2)=            2  f( 3)=            3  f( 4)=            5  f( 5)=            8  
f( 6)=           13  f( 7)=           21  f( 8)=           34  f( 9)=           55  f(10)=           89  
f(11)=          144  f(12)=          233  f(13)=          377  f(14)=          610  f(15)=          987  
f(16)=        1,597  f(17)=        2,584  f(18)=        4,181  f(19)=        6,765  f(20)=       10,946  
f(21)=       17,711  f(22)=       28,657  f(23)=       46,368  f(24)=       75,025  f(25)=      121,393  
f(26)=      196,418  f(27)=      317,811  f(28)=      514,229  f(29)=      832,040  f(30)=    1,346,269  
f(31)=    2,178,309  f(32)=    3,524,578  f(33)=    5,702,887  f(34)=    9,227,465  f(35)=   14,930,352  
f(36)=   24,157,817  f(37)=   39,088,169  f(38)=   63,245,986  f(39)=  102,334,155  f(40)=  165,580,141  
f(41)=  267,914,296  f(42)=  433,494,437  f(43)=  701,408,733  f(44)=1,134,903,170  f(45)=1,836,311,903

Similarly, using long would allow to fit only 91 Fibonacci numbers.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement