Assume that you have an array of integers named a. Which of these code segments print the same results?

int i = 1;
while(i < a.length)
{
System.out.println(a[i]);
i++;
}

int i;
for (i = 0; i < a.length; i++)
{
System.out.println(a[i]);
}

for (int i : a)
{
System.out.println(i);
}
I and II only
II and III only
I and III only
All three print the same results.
All three print different results.

Respuesta :

Answer: II and III only

The first code will print starting with the second variable in the array. So it will start with array[1] instead of starting with array[0]

The second code will start from array[0] as the variable i is 0. It will print the first value in the array before proceeding to increment the value of i.

The third code will also start from array{0] as the program will check for the first value of a before proceeding to the next one.

An example would be if we were to define the array as:

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

1st Code Output:

2

3

4

5

2nd Code Output:

1

2

3

4

5

3rd code Output:

1

2

3

4

5

Always remember that arrays will always begin from 0.

Answer:

ii and iii only

Explanation:

=> Analysis of the first code snippet;

int i = 1;

while(i < a.length)

{

System.out.println(a[i]);

i++;

}

The code initializes the variable i to 1 and then loops from i=1 to one less than the length of the array a. At each of the loop, the corresponding element of the array at the index specified by the variable i is printed. And since i is starting at 1, the first element of the array (the one at index 0) will not be printed. Other elements in the array will be printed.

=> Analysis of the second code snippet;

int i;

for (i = 0; i < a.length; i++)

{

System.out.println(a[i]);

}

The code initializes the variable i to 0 and then loops from i=0 to one less than the length of the array a. At each of the loop, the corresponding element of the array at the index specified by the variable i is printed. And since i is starting at 0, the first element of the array (the one at index 0) will be printed. Other elements in the array will also be printed. In other words, all of the elements in the array will be printed.

=> Analysis of the third code snippet;

for (int i : a)

{

System.out.println(i);

}

The code uses the enhanced for version to print all the elements in the given array a. In the code each element in the array a is represented by i at various loop cycles. Therefore all the elements in the array a will be printed.

In summary, ii and iii will produce the same results.