Login | Register

The For Loop

January 4, 2008, 21:35 by e_barroga
[loading]
-->
The for loop is a very simple concept that anyone can understand. In basic terms, it is a loop; a loop with a special format.

Let's look at its basic format:

for (i=0; i<10; i+=1) {
slot[i] = -1;
}


There you go! A simple example of a for loop. But let's get into deeper detail with each line.

The [b]for loop[b]'s general syntax is as follows:
for (<statement1>; <check>; <statement3>;) <statement2>

-The loop begins with an initial statement (it can be any statement, as long as it is a statement).
-After the initial statement, the loop does a check (verifing that the check equals true).
-If the check returns true, the loop proceeds, otherwise, the loop ends.
-Another statement is performed, followed by the last statement.

Let's look at another example. Say we wanted to initialize an array:

slot[0] = -1;
slot[1] = -1;
slot[2] = -1;
slot[3] = -1;
slot[4] = -1;


That was a pretty easy job for the programmer, but it could have been abit tedious if we wanted to go up to 10, or even 100.

That's where the for loop comes in handy. Let me show you.


for (i=0; i<5; i+=1) slot[i] = -1;


-The first statement is: i=0.
-Next thing we se is: [i]i<5[/b]. So the loop checks if i is smaller than 5, since it is... the loop continues.
-slot[i] = -1; is the next statement. So, since i is equal to 0, slot[0] equals -1.
-After that, the last statement is executed, which is: i+=1. That basically, makes i 1 more greater (which is 0+1 = 1).

Now, the loop performs the check again: i<5. Since, i equals 1, the check returns true...proceeding to the next statement: slot[i] = -1; which translates: slot[1] = -1;.

The loop continues until i is no longer smaller than 5.

So this:

for (i=0; i<5; i+=1) slot[i] = -1;


is the same as:

slot[0] = -1;
slot[1] = -1;
slot[2] = -1;
slot[3] = -1;
slot[4] = -1;


It doesn't exactly seem very useful, but by changing 5 to 100, or even 1000, you'll see how useful it becomes.

//Initialize a "1000" long array with the value -1
for (i=0; i<1000; i+=1) slot[i] = -1;


Hopefully, this gives you a better concept with the for loop.

Comments

Loading comments... [loading]
.
Users logged in:

game maker articles, game maker examples, game maker tutorials, gmtutorials, game maker questions and answers, game maker crash course, how to create games