235k views
5 votes
What is stored in alpha after the following code executes?

int[] alpha = new int[5];
int j;

for (j = 0; j < 5; j++)
{
alpha[j] = 2 * j;

if (j % 2 == 1)
alpha[j - 1] = alpha[j] + j;
}

1. alpha = {0, 2, 4, 6, 8}
2. alpha = {0, 2, 9, 6, 8}
3. alpha = {3, 2, 9, 6, 8}
4. alpha = {0, 3, 4, 7, 8}

1 Answer

3 votes

Answer:

Option 3: alpha = {3, 2, 9, 6, 8}

Step-by-step explanation:

Given an an array, alpha, with 5 integer elements.

What happen inside the for-loop is that

  1. The current index-j will be multiplied by 2 and then assigned as the value of the element of the array indexed by j.
  2. If the index-j is an odd number (j % 2 == 1), the previous element of the array, alpha[j - 1] will be assigned with value of alpha[j] + j. For example, given the alpha[0] = 0. If j = 1, alpha[j - 1] = alpha [0] = alpha[1] + 1= 2 + 1 = 3
  3. In short, the elements with even index-j are simply equal with 2 * index-j. Whereas the elements with odd index-j will always equal to alpha[j - 1] = alpha[j] + j

User Kris
by
5.1k points