The most common form of a for loop uses a new variable as a loop and loop counter from zero to (but not including) the upper limit.
This loop will go from 0 to 9:
for (int i = 0; i < 10; i++) {
You can name a loop variable anything that makes sense. Unless you have a good name, the names i , j and k are the old convention for naming variables for small loops.
The point of using < 10 instead of <= 9 is that you loop more than ten elements. If you iterate over elements in an array, you use the length of the array in the condition:
for (int i = 0; i < anArray.Length; i++) {
There are three statements inside the for loop. Initializer, loop condition, and post-update. The loop above creates the same code as if you were executing a loop with while :
int i = 0; while (i < 10) {
You can put whatever you like into three statements in a for loop, but you should try to stick to this general form. This is how the for loop is usually used, and people will easily understand what the loop does.
Guffa source share