Home / Questions / What will be the output of the following program segment? int ar[] = {1, 2, 3, 4, 5}; int a = 1; for (int i = 0; i < 7; i++) { a = a + i * ar[i]; } System.out.println(a);
Explanatory Question

What will be the output of the following program segment?

int ar[] = {1, 2, 3, 4, 5};
int a = 1;

for (int i = 0; i < 7; i++) { 
    a = a + i * ar[i];
}

System.out.println(a);

👁 94 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

Array out-of-bounds issue:

The array ar has only 5 elements (ar[0] to ar[4]).

The loop runs from i = 0 to i = 6, which will attempt to access ar[5] and ar[6]. These indices are out of bounds, and the program will throw an ArrayIndexOutOfBoundsException at runtime.