I have a doubt with the behavior of a decremental FOR loop. When it reaches 0 it does not enter. I explain myself with the code...
int z = 10;
for (int i = 20; i > 0; i--)
{
if (i == 0)
{
z = 100;
}
}
Console.WriteLine(z);
If you look closely, it is assumed that when i==1
the FOR is fulfilled, and the last thing it should do is decrement to the value i==0
, so that the last loop of the i loop should be 0 and enter the IF. What really happens (checking by debugging line by line in VisualStudio) is that the code actually decrements i (reducing it to 0), then checks if it is greater than 0, and since it is not, it does not enter the FOR, nor, as a consequence, in the IF.
I have consulted the Microsoft reference regarding FOR ( https://docs.microsoft.com/es-es/dotnet/csharp/language-reference/keywords/for ) and it says that
the iterator section defines what happens after each iteration of the loop body
Overall, I understood that the FOR loop had three sections (initializer, condition and iterator), and that they were executed in that order... Either someone explain it to me, or I'm more lost than anyone; it is as if the sequential reading of the code were backwards.
What you say is totally true.
The FOR loop consists of 3 parts
for (inicializador, condición, iterador)
The for is executed as written.As you will have verified in the first initialization,
i
it is ok20
. It's not until you've done all the instructions that theiterador
. It would not make sense just to enter to execute theiterador
.So for the last case, and where you have the problem:
The value of
i
vale1
, evaluates thecondición
and as it istrue
enters insidefor
and executes all the instructions. Once the is done, decrement the value ofi
a0
.Now re-evaluate the condition
i
asi > 0
being false, end thefor
.your problem is in this part
the
i
is decremented until it only reaches 1. if you want it to reach 0 it should be like thisin this way it would enter the if condition