Var within FOR when it starts at 0 (zero) should Count be Count-1?

2

I picked up a system in the company where I work for another colleague. I note that all FOR's are like this:

for(int i = 0; i < lista.count; i++)
{
  //meu código
}

I learned that when a variable within FOR starts with zero, my COUNT must always be Count - 1 , unless there is a specific rule for it to occur. Am I right?

    
asked by anonymous 12.03.2015 / 20:03

1 answer

6

Yes, you're right, it's basic math. If you have 10 elements, and start counting go from 0 to 9: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

Count tells you how many elements you have in the list. Then you should count to the count prior to counting using Count - 1 .

Unless you have some reason to use it differently but you usually do not have it, and even if it does, it would have to be a smaller value yet. Of course, if you try to access a equal number element at the count it will raise an exception.

Notice the highlight of the "equal" up there. This is true if you are using the <= comparison operator.

In your example you are using < , so you do not need to -1 . Why it will stop an element before it comes to an end.

See this code demonstrated the difference:

using System.Console;
using System.Collections.Generic;

public class Program {
    public static void Main() {
        var lista = new List<int>();
        for (var i = 0; i < 10; i++) { //criando a lista com 10 elementos
            lista.Add(i);
        }
        for (var i = 0; i < lista.Count; i++) { //contando de 0 ao Count com <
            WriteLine(lista[i]);
        }
        for (var i = 0; i <= lista.Count - 1; i++) { //contando até Count - 1 com <=
            WriteLine(lista[i]);
        }
    }
}

See working on dotNetFiddle .

When you use <= one more element is caught because of equal. The < takes all that are less, but the <= takes all that are smaller plus the element that is equal.

In general I prefer the first, have a less mathematical operation to do. Not that this necessarily means that it is faster, but it is simpler. As I demonstrated in that other answer , what everyone expects can be false and only testing to assert which is faster. It may be that making a "lesser or equal" is slower than doing a "minor" and a "subtraction."

Another detail that may be just a typo is that the property that shows the number of elements in the list is Count . It is not COUNT and is not count .

Certainly I would use foreach in this case and I would not worry about it. I have already shown in the linked answer above that it is equal to or better than for in performance and is simpler. Besides being semantically more correct. The for above is telling you to get all the elements, which is exactly why foreach exists. And he guarantees that everything will be correct in the process. It is simpler in every way. The for would only be useful if it is important that you have an index number of the element in the list.

    
12.03.2015 / 20:06