Saturday, 24 November 2012

Episode 7: Using for loops



Episode 7: Using for loops

The most basic for loops are based on a counter. You set the beginning value for the counter, set the ending value, and set how the counter is incremented each time the statement block is executed. Building for loops The general format of a basic for loop is as follows:

for (startingvalue;endingcondition;increment)
{
block of statements;
}

Within the for statement, you need to fill in the following values:

startingvalue: The startingvalue is a statement that sets up a variable to be your counter and sets it to your starting value. For exam ple, the statement $i=1; sets $i as the counter variable and sets it equal to 1. Frequently, the counter variable is started at 0 or 1. The starting value can be a number, a combination of numbers (such as 2 + 2), or a variable.

endingcondition:  The endingcondition is a statement that sets your ending value. As long as this statement is true, the block of statements keeps repeating. When this statement is not true, the loop ends. For example, the statement $i<10; sets the ending value for the loop to 10. When $i is equal to 10, the statement is no longer true (because $i is no longer less than 10), and the loop stops repeating. The statement can include variables, such as $i<$size;.
increment: A statement that increments your counter. For example, the statement $i++; adds 1 to your counter at the end of each block of statements. You can use other increment statements, such as $i=+1; or $i--;.

A basic for loop sets up a variable, like $i, that is used as a counter. This variable has a value that changes during each loop. The variable $i can be used in the block of statements that is repeating. For example, the following simple loop displays Hello World! three times:

for ($i=1;$i<=3;$i++)
{
echo “$i. Hello World!<br />”;
}

The following is the output from these statements:
1. Hello World!
2. Hello World!
3. Hello World!

Written by “Shojib”

No comments:

Post a Comment