Reputation: 59
The method in the class accepts an integer from a user to remove from the list. The code works. The problem I have is that I don't understand why it works; indeed, from what I know, it shouldn't work.
public void Remove(int ValueToRemove)
{
bool isFound = false;
for (int count = 0; count < CurrentIndex; count++)
{
if (list[count] == ValueToRemove && !isFound)
{
isFound = true;
CurrentIndex = CurrentIndex -1;
}
if (isFound && ((count + 1) < list.Length))
{
list[count] = list[count + 1];
}
}
}
Shouldn't the statement...
if(list[count] == ValueToRemove && !isFound)
...always evaluate as false, therefore skip running the code inside the braces? Isn't !isFound the equivalent of evaluating
if(list[count] == ValueToRemove && isFound == true)
In the code...
if (list[count] == ValueToRemove && !isFound)
{
isFound = true;
CurrentIndex = CurrentIndex -1;
}
...if CurrentIndex = CurrentIndex - 1, making CurrentIndex equal one less than what it did, what happens to the previous index?
Lastly...
if (isFound && ((count + 1) < list.Length))
{
list[count] = list[count + 1];
}
...does the value of list[count] equal the value of the next index (ex. index 5 equals whatever value was in index 6), or does the value contained within that index equal one higher (ex. if index 5 contains the value of 10, then index 5 will now equal 11)
Upvotes: 0
Views: 170
Reputation: 8592
To answer your question about this:
if (isFound && ((count + 1) < list.Length))
{
list[count] = list[count + 1];
}
The condition first checks to see if the next index exists, and then assigns the value of that next index to the current value. In other words, if count = 5, it first checks to make sure list[6] won't cause an undefined offset, and then list[5] = list[6] would assign the value from list[6] to list[5]. So if list[5] was 10 and list[6] was 11, list[5] becomes 11.
Upvotes: 0
Reputation: 4808
Since isFound
is false, !isFound
evaluates to true and the if statement is entered.
This means that !isFound
is the same as saying:
isFound == false
...if CurrentIndex = CurrentIndex - 1, making CurrentIndex equal one less than what it did, what happens to the previous index?
Nothing happens to the previous index, instead the loop is repeated on the current item in the list.
...does the value of list[count] equal the value of the next index (ex. index 5 equals whatever value was in index 6), or does the value contained within that index equal one higher (ex. if index 5 contains the value of 10, then index 5 will now equal 11)
It takes the value of the next item in the list and assigns it to list[count]
.
You can answer a lot of these types of questions yourself by setting breakpoints and debugging through the code, seeing what is happening and checking values as you go.
Upvotes: 7