Given the code fragment:



int[] lst = {1, 2, 3, 4, 5, 4, 3, 2, 1};
int sum = 0;
for (int frnt = 0, rear = lst.length - 1; frnt < 5 && rear >= 5; frnt++, rear--) {
    sum = sum + lst[frnt] + lst[rear];
}
System.out.print(sum);

What is the result?

A.

20

B.

25

C.

29

D. Compilation fails
E. An ArrayIndexOutOfBoundsException is thrown at runtime

題解

程式第8行的for迴圈使用了兩種計次變數,分別是frnt和rear。frnt的範圍在0~4,rear的範圍在8~5。

迴圈第一次執行,frnt = 0、rear = 8,sum = 0 + 1 + 1 = 2。

迴圈第二次執行,frnt = 1、rear = 7,sum = 2 + 2 + 2 = 6。

迴圈第三次執行,frnt = 2、rear = 6,sum = 6 + 3 + 3 = 12。

迴圈第四次執行,frnt = 3、rear = 5,sum = 12 + 4 + 4 = 20。

迴圈正要執行第五次時,frnt = 4、rear = 4,rear變數已經小於5了,因此跳出迴圈,輸出sum變數的值。