Could someone explain in the simplest terms, as if you are talking to an idiot (because you are), what this code is actually saying/doing
for (int i = 0; i < 8; i++)
That's a loop that says, okay, for every time that i
is smaller than 8, I'm going to do whatever is in the code block. Whenever i
reaches 8, I'll stop. After each iteration of the loop, it increments i
by 1 (i++
), so that the loop will eventually stop when it meets the i < 8
(i
becomes 8, so no longer is smaller than) condition.
For example, this:
for (int i = 0; i < 8; i++)
{
Console.WriteLine(i);
}
Will output: 01234567
See how the code was executed 8 times?
In terms of arrays, this can be helpful when you don't know the size of the array, but you want to operate on every item of it. You can do:
Disclaimer: This following code will vary dependent upon language, but the principle remains the same
Array yourArray;
for (int i = 0; i < yourArray.Count; i++)
{
Console.WriteLine(yourArray[i]);
}
The difference here is the number of execution times is entirely dependent on the size of the array, so it's dynamic.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With