Click here to Skip to main content
15,886,689 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Suppose that we are given the following code:

int[] myArray = {4, 5, 6, 1, 2, 3, 21, 20};
for (int i = 0; i < 5; i++) {
myArray[i] = myArray[length -1 - i];
}

After it is executed what will the array myArray contain?

What I have tried:

I am not sure what length means in this question. If length means 5, I think the answer is{0, -1, -2, 3, 2, 1, -17, -16}. If length means how many value in this Array, it should be 8, the answer should be {3, 2, 1, 6, 5, 4, -14, -13}
Posted
Updated 8-Jul-16 9:33am
Comments
Matt T Heffron 8-Jul-16 17:08pm    
You are correct, the question is ill-stated.
You could answer that the code will not compile because length has not been declared.
It seems most likely that length means the length of myArray (i.e., 8)
Using the answer you gave above would probably be the best strategy.
It shows critical thinking.

Run it through the debugger and it'll become clear.
i varies with each pass through the loop: 0, 1, 2, 3, 4
So the element you put the value into starts with teh first and moves on to teh second, and so on.
The value changes as well, but it starts with:
C#
myArray[length -1 - 0]

And then uses
C#
myArray[length -1 - 1]
And so forth.
So the if length is 5 (which is wrong for myArray - it should be 8) then the indexes you load from are 4, 3, 2, 1, 0
So element 0 becomes element 4: 2
Element 1 becomes element 3: 1
Element 2 becomes element 2: 6
Element 3 becomes element 1 (which has changed): 1
Element 4 becomes element 0 (which has changed): 2

Seriously: use the debugger and you'll see what I mean!
 
Share this answer
 
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

Execute the program line by line and inspect variables as the program executes
C++
int tmp;
int[] myArray = {4, 5, 6, 1, 2, 3, 21, 20};
for (int i = 0; i < 5; i++) {
    tmp= length -1 - i;
    myArray[i] = myArray[length -1 - i];
}

The tmp will just show you where it get the value in next line.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900