Search code examples
c#for-looppalindrome

Why doesn't my c# for loop get entered?


I'm new to C# and I'm trying to get a simple isPalindrome method to work. Basically my for loop never gets entered. I tried giving it the string "hannah", and it never prints a single one of the Console.writeline method calls in the body of the for loop. But both of the WriteLine calls before the for loop return true for "hannah", so it should enter the for loop and print out at least one statement from the for loop body. What's wrong with my loop?

private static Boolean isPalindrome(string s)
{
    int counter = 0;
    if (s.Length == 1)
    {
        return true;
    }

    Console.WriteLine(s[counter]==s[(s.Length - counter - 1)]); //this returns true
    Console.WriteLine((counter != (s.Length / 2))); //this returns true

    for (; (counter != (s.Length / 2)) & (s[counter] == (s.Length - counter - 1)); counter++)
    {
        Console.WriteLine("s[counter is {0} and s.length-counter-1 is", s[counter], s[(s.Length -                   counter - 1)]);

        //The above line never prints; why doesn't my for loop get entered?
    }

    if((counter == (s.Length / 2))) {
        return true;
    }

    return false;
}

Solution

  • Change second part of your condition to (s[counter] == s[s.Length - counter - 1]).

    Otherwise you're comparing numeric representation of s[counter] with s.Length - counter - 1, not the character under that index.