Multiple choice

What is the output of the following Java program?

public class test { public static void main(String[] args) { try { int a[]=new int[8]; a[0]=0; a[1]=1; for(int i=2;i<=a.length-1;i++) { a[i]=a[i-1]+a[i-2]; System.out.println(a[i]+" "); }
} catch(Exception e) { System.out.println(e); } }

}

  1. 1 2 3 4 5 6

  2. 1 2 3 5 8

  3. 1 2 3 5 8 13

  4. 1 2 3 5 8 13 21

  5. Error in the program

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

int a[]=new int[8]; //creates integer array of size 8.First two elements of the array are initialized with 0,1 respectively and the logic is other elements in the array are computed by adding the previous two elements. a[2]=a[1]+a[0]=1+0=1; a[3]=a[2]+a[1]=1+1=2; a[4]=a[3]+a[2]=2+1=3; a[5]=a[4]+a[3]=3+2=5; a[6]=a[5]+a[4]=5+3=8; a[7]=a[6]+a[5]=8+5=13; a[7] is last element which is computed because a.length-1=8-1=7; Hence, the output is 1 2 3 5 8 13