Owen Hodgson
Owen Hodgson

Reputation: 37

Trouble whilst creating a while loop

So i was given this question below to answer and I initially created a for loop to do this which worked fine but i was told i could also do it in a while loop which is what i am trying now however i am not sure where I've gone wrong in my code below as i'm getting a indexoutofrange exception.

Question 4 - Write a piece of software that compares two strings and outputs the number of characters in the same position. E.g. “helloworld” and “worldhello” would output 2 as there are two l’s in the same positions compare the strings below to calculate your answer.

String1 - "helloworld" String2 - "worldhello"

My for loop code which works perfectly

        string string1 = "helloworld";
        string string2 = "worldhello";

        int list = 0;
        for (int i = 0; i < string1.Length; i++)
        {
            if (string1[i] == string2[i]) 
            {
                list = list + 1;
            }
        }
        Console.WriteLine(list);

Now this is my while loop code which isn't working

        string string1 = "helloworld"; 
        string string2 = "worldhello"; 
        int i = 0;
        int total = 0;
        while (i < string1.Length)
        {
            i++;
            if (string1[i] == string2[i])
            {
                total = total + 1;
            }
        }

Upvotes: 0

Views: 63

Answers (1)

Sweeper
Sweeper

Reputation: 271410

You are nearly there!

The third part of the for loop (i++) will run at the end of each iteration, so you should not put i++; as the first statement in the while loop version. You should put it as the last statement:

while (i < string1.Length)
{
    if (string1[i] == string2[i])
    {
        total = total + 1;
    }
    i++;
}

In general, a for loop of the form:

for (x ; y ; z) { w; }

can be written as a while loop like this:

x;
while (y) {
    w;
    z;
}

Upvotes: 1

Related Questions