174k views
2 votes
Consider the partially-filled array named a. What does the following loop do? (cin is a Scanner object)

int[] a = {1, 3, 7, 0, 0, 0};
int size = 3, capacity = 6;

int value = cin.nextInt();
while (size < capacity && value > 0)
{
a[size] = value;
size++;
value = cin.nextInt();
}

1. Reads one value and places it in the remaining first unused space endlessly.
2. Crashes at runtime because it tries to write beyond the array.
3. Reads up to 3 values and places them in the array in the unused space.
4. Reads up to 3 values and inserts them in the array in the correct position.

1 Answer

5 votes

Answer:

3. Reads up to 3 values and places them in the array in the unused space.

Step-by-step explanation:

cin.NextInt() reads the next value from the Scanner.

The while is just while the size is lesser than the capacity and the value is positive. It may read up to 3 values, and puts at the position size; Size starts at 3, that is, the first index which the value is 0, and goes up to 5. So it is the unused positions.

The correct answer is:

3. Reads up to 3 values and places them in the array in the unused space.

User Radoslawik
by
5.8k points