202k views
0 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;}

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

User AterLux
by
6.4k points

1 Answer

5 votes

Answer:

Option 2: Reads one value and places it in the remaining first unused space endlessly.

Step-by-step explanation:

Given the code as follows:

  1. int[] a = {1, 3, 7, 0, 0, 0};
  2. int size = 3, capacity = 6;
  3. int value = cin.nextInt();
  4. while (size < capacity && value > 0)
  5. {
  6. a[size] = value;
  7. }

The a is an array with 6 elements (Line 1). The program will prompt the user for an integer and assign it to variable value (Line 3).

The while loop have been defined with two conditions, 1) size < capacity and value > 0. The first condition will always be true since the size and capacity are constant throughout the program flow and therefore size will always smaller than capacity.

Hence, if user input an integer larger than 0, the while loop will infinitely place the same input value to the remaining first unused space of the array, a[3].

User Nikhil Kinkar
by
6.4k points