Bustedspoke Bustedspoke - 1 month ago 8
C# Question

What is the meaning of "-1" in the following C# code?

Hey guys I'm just starting to learn C# and I was wondering what the "-1" in the for loop meant?

string[] fruit = { "Apples", "Oranges", "Grapes" };
for (int i = fruit.Length - 1; i >= 0; i--)
{
// Code Here
Console.WriteLine(fruit[i]);
}


I was trying to figure out how to go backwards in an array and I was able to do it, but I just want to know how the "-1" works in the for loop. Why is it necessary?

Answer

Arrays in C# are 0-indexed, meaning they begin at element [0]. Thus, the largest accessible index is Length-1.