2

I'm taking a c# course and it has given me some code I copy and paste and some I do myself. Anyways, I don't understand in this for() loop why would we subtract 1 from the int i = target.Length property?

static string reverseString(string target)
{
    String result = "";

    // walk the target string backwards
    for (int i = target.Length - 1; i >= 0; i--)
    {
        // add this letter to the result
        result += target[i];
    }

    // return the result to the calling code
    return result;
}
Deniz
  • 429
  • 1
  • 4
  • 19
Samurai
  • 189
  • 10
  • Because indexes start from 0 in C# and most other languages. – Ian Mercer Feb 13 '18 at 02:28
  • 3
    It is because the index starts at `Zero`. Assuming you have a string of `DOG`, then each character's index are `D = 0, O = 1, G = 2`. If you don't subtract it by 1, by the time it reaches `target[3]`, it will throw *Index was outside the bounds of the array.* exception. – John Woo Feb 13 '18 at 02:33
  • Be aware that “walking a string backward” [does not reverse it](https://stackoverflow.com/questions/228038/). – Dour High Arch Feb 13 '18 at 02:34
  • @John Woo Oh, that makes sense I was confused because instead of subtracting 1 from target.Length and setting the loop not to end until i >= 0 it would of made more sense for it just to be (int i = target.Length ; i > 0; i--) – Samurai Feb 13 '18 at 02:36
  • @Samurai If your loop conditional goes from `target.Length` down to zero you need to access `target[i - 1]` on each iteration, else you will out of the bounds of the array on the first iteration of the loop. In this case, it's not much of a difference, but it's generally preferable that `i` be the index of whatever you're accessing by the time you're in the loop body, because you may need to use it at multiple points in the body, and remembering to calculate `i - 1` at each location is more likely to have you forget a location and create a bug in your code. – Preston Guillot Feb 13 '18 at 02:41

2 Answers2

1

Take this example.

string target = "ABC";
// target can be thought of as an array of characters
// target[0] holds 'A'
// target[1] holds 'B'
// target[2] holds 'C'

int length = target.Length; 
// length would be 3 because Length is the count of the chars
// but if you were to try and get the value of target[3] you would get an error 
// because target ends at [2] (index 2)

So you need to start at .Length - 1 and work backwards to 0 (not 1).

Michael Hudson
  • 1,330
  • 4
  • 21
  • 25
0

It starts at Length - 1 because that is the last allowable index. Note it also includes index 0 (because of the ">= 0") which is the first allowable index. The increment is -1 so we consider decreasing values of the index instead of increasing ones.

Samuel Neff
  • 73,278
  • 17
  • 138
  • 182
sjb-sjb
  • 1,112
  • 6
  • 14