Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

Why we use -1 within a for Loop c#

I have code which checks if a word if a palindrome or not. Within the for loop there is a -1 value. Can someone explain to me why -1 is used after the name.Length in c#

 public static void Main()
    {

        string name = "Apple";
        string reverse = string.Empty;

        for (int i = name.Length - 1; i >= 0; i--)

        {
            reverse +=name[i];
        }

        if (name == reverse)
        {
            Console.WriteLine($"{name} is palindrome");
        }else
        {
            Console.WriteLine($"{name} is not palindrome");
        }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's because whoever wrote the code, wanted to write:

reverse += name[i];

String operator [] takes values from 0 upto (string's length-1). If you pass length or more, you will get an exception. So, code's author had to ensure that i==Length won't be ever passed there. So it starts from Length-1 and counts downwards.

Also, note that the other bound of i is 0 (>=, not >, so 0 is included), so the loop visits all values from 0 to length-1, so it visits all characters from the string. Job done.

However, it doesn't have to be written in that way. The only thing is to ensure that the string operator [] wont see values of of its range. Compare this loop, it's identical in its results:

    for (int i = name.Length; i >= 1; i--)
    {
        reverse += name[i-1];
    }

Note that I also changed 0 to 1.

Of course, it's also possible to write a loop with the same effects in a lot of other ways.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...