Which of the following loops would adequately add 1 to each element stored in values?

Which of the following loops would adequately add 1 to each element stored in values?

Assume values is an int array that is currently filled to capacity, with the following values:

a) for(j=1;j<values.length;j++) values[j]++;

b) for(j=0;j<values.length;j++) values[j]++;

c) for(j=0;j<=values.length;j++) values[j]++;

d) for(j=0;j<values.length–1;j++) values[j]++;

e) for(j=1;j<values.length–1;j++) values[j]++;

Answer: b. Explanation: The first array element is values[0], so the for-loop must start at 0, not 1. There are values.length elements in the array where the last element is at values.length–1, so the for loop must stop before reaching values.length. This is the case in b. In d, the for loop stops 1 before values.length since “<” is being used to test the condition instead of <=. 


Java

Learn More Multiple Choice Question :