FANDOM


Loops are basically if statements that repeat themselves until the condition within them is false or the user ends the code. Their are two different type of loops. For loops and while loops.


For Loop

For loops have the ability to increase/decrease a number by any amount you want. The syntax for the for loop goes as follows...

for( < variable > ; < condition > ; < increment > )
{
    // execute until the "condition" is false
}

Example use:

for( i = 0 ; i < 21 ; i++ )
{
    // run this 21 times
}

The above intializes the variable "i" to be equal to 0 and then checks to see if "i" is smaller than 21 and if it is, add one to "i".


The for loop can take three optional aguments which operate something like this.

for( < variable > ; < condition > ; < increment > )

< variable >      // initialize a variable here
< condition >     // check if this condition is true before moving on to the next part
< increment >     // do this to the variable if the condition is met


None of the arguments within the for loop are required or need to be executed their. You can do anything like what is shows below.

i = 0;
for( ; i < 50; i++ )
{
    // do this 50 times
}

or

for( i = 0; i < 100 ; )
{
    i++;
    // increase until "i" is above 100
}


If you want a for loop to never end, you can leave the arguments blank. Since the condition inside the loop will never be false, it will continue indefinitly.

for( ;; )
{
    // infinite loop   
}



While Loop

While loops are almost the exact same as for loops. They check if the condition within the parenthesis is true and continue running the code inside the curly braces until the condition becomes false or until the user ends the code.

The while loops syntax goes as follows.

while( < condition > )
{
    // execute until the "condition" is false
}


Example of an infinite while loop:

while( 1 )
{
    // execute this
}

or

while( true )
{
    // execute this
}

Since "1" and true cannot be set to false, the loop will keep repeating until the user decides to end the code.

For a more in depth description of the while loop, read the if statement tutorial. The while loop is basically an if statement that keeps repeating until the condition is false.