for (int i = 0; i < 8; i++) {
//code
}
In simplest terms
int i = 0;
if (i < 8) //code
i = i + 1; //i = 1
if (i < 8) //code
i = i + 1; //i = 2
if (i < 8) //code
i = i + 1; //i = 3
if (i < 8) //code
i = i + 1; //i = 4
if (i < 8) //code
i = i + 1; //i = 5
if (i < 8) //code
i = i + 1; //i = 6
if (i < 8) //code
i = i + 1; //i = 7
if (i < 8) //code
i = i + 1; //i = 8
if (i < 8) //code - this if won't pass
for
(int i = 0; i < 8; i++)
It's a for
loop, which will execute the next statement a number of times, depending on the conditions inside the parenthesis.
for (int i = 0; i < 8; i++)
Start by setting i = 0
for (int i = 0;i < 8; i++)
Continue looping while i < 8
.
for (int i = 0; i < 8;i++)
Every time you've been around the loop, increase i
by 1.
For example;
for (int i = 0; i < 8; i++)
do(i);
will call do(0), do(1), ... do(7) in order, and stop when i
reaches 8 (ie i < 8
is false)
it's the same as think the next:
"starting with i = 0, while i is less than 8, and adding one to i at the end of the parenthesis, do the instructions between brackets"
It's also the same as:
while( i < 8 )
{
// instrucctions like:
Console.WriteLine(i);
i++;
}
the For sentences is a basis of coding, and it's as useful as necessary its understanding.
It's the way to repeat n-times the same instrucction, or browse ( or do something with each element) an array
The generic view of a loop is
for (initialization; condition; increment-decrement){}
The first part initializes the code. The second part is the condition that will continue to run the loop as long as it is true. The last part is what will be run after each iteration of the loop. The last part is typically used to increment or decrement a counter, but it doesn't have to.
for(<first part>; <second part>; <third part>)
{
DoStuff();
}
This code is evaluated like this:
So for your example:
for (int i = 0; i < 8; i++)
{
DoStuff();
}
So the loop runs one time with i set to each value from 0 to 7. Note that i is incremented to 8, but then the loop ends immediately afterwards; it does not run with i set to 8.
Source: Stackoverflow.com