user8716535
user8716535

Reputation:

Method in C# counting doesn't count

I have this Method:

public int IndexOf(string text)
        {

            for (Node i = Head; i != null; i = i.Next)
            {
                int counter = 0;
                if (text == i.Text)
                {
                    return counter;
                }

                counter++;
            }
            return -1;
        }

Now I have 4 strings in my list, and the Index is always 0. I can't find out where the problem is.

Thanks,

Upvotes: 1

Views: 927

Answers (2)

Prasad Telkikar
Prasad Telkikar

Reputation: 16079

You are initializing counter = 0 in for loop, initialize counter variable outside of it.

In your case, Counter variable is initialized to 0 inside for loop, for each iteration counter variable becoming zero and at the end of loop it is incrementing by one.

If you print value of counter while initialization and increment, you will understand what modification you want in your code.

public int IndexOf(string text)
        {

            for (Node i = Head; i != null; i = i.Next)
            {
                int counter = 0;
                Console.WriteLine("Value of counter = "+ counter);
                if (text == i.Text)
                {
                    return counter;
                }

                counter++;
                Console.WriteLine("Value of counter post increment = "+ counter);
            }
            return -1;
        }

I pointed out where are you going wrong. Other answers will show you what changes you need to do in your code.

Upvotes: 6

programtreasures
programtreasures

Reputation: 4298

You should initialize counter variable out of loop,

    public int IndexOf(string text)
    {
        int counter = -1;
        for (Node i = Head; i != null; i = i.Next)
        {
            counter++;
            if (text == i.Text)
            {
                return counter;
            }                
        }
        return -1;
    }

Upvotes: 0

Related Questions