25.8k views
4 votes
Suppose that a is a one-dimensional array of ints with a length of at least 2. Which of the following code fragments successfully exchange(s) the values of the first two elements of a?I a[ 0 ] = a[ 1 ];a[ 1 ] = a[ 0 ];II int t = a[ 0 ];a[ 0 ] = a[ 1 ];a[ 1 ] = t;III a[ 0 ] = a[ 0 ] - a[ 1 ];a[ 1 ] = a[ 0 ] + a[ 1 ];a[ 0 ] = a[ 1 ] - a[ 0 ];A) I onlyB) II onlyC) III onlyD) I and II onlyE) II and III only

1 Answer

3 votes

Answer:

E)II and III only

Explanation:

This can be seen with examples. Say a[0]=1 and and a[1]=2.

for I , the first line of code would be:

a[0]=a[1];

thus, we would get a new value for a[0]=2.

The second line of code

a[1]=a[0]; uses the new value of a[0], so we would get a[1]=2.

The end result is a[0]=2, and a[1]=2 which doesn't exchange the values of the first two elements.

For II the first line of code

int t= a[0]; saves the original value of a[0] to t, so we get t=1.

the second line of code

a[0]=a[1]; changes the value of a[0] to that of a[1]. Thus, in our example a[0]=2.

the final line

a[1]=t; changes the value of a[1] to the original value of a[0], giving us a[1]=1 and a[0]=2, what we were looking for.

For III

the first line of code

a[0]=a[0]-a[1];

gives us

a[0]=1-2

the secon line

a[1]=a[1]+a[0];

takes the new value of a[0] and replaces it in the expression

a[1]= 2+(1-2)=1

the last line

a[0]=a[1]-a[0];

takes the new value of a[0] and a[1] and replaces the in the expression

a[0]=1-(1-2)=1-1+2=2

which exchanges the values needed.

So we can see that only II and III do what we require, giving us E as the answer.

User Ahmad Ferdous
by
5.6k points