C Plus Plus for
From GMpedia.org Wiki
The C++ for loop is a for loop that is used in the C++ Programming language.
Contents |
[edit] Syntax
The for loop contains three things before the actual execution of code:
for (<initialization>; <while-condition>; <between-loops expression>)
Three statements are written inside the for brackets, all are seperated by semicolens. Each semicolen marks the end of a statement and the beginning of the other.
- The <initialization> expression is executed once before the loop, it usually defines the variable that will be used as a counter. For example:
i=0
- In the example above, the variable i is set to 0. If this code was not called, i might have another value from previous for statements and the result will not be as expected.
- The <while-condition> is a condition (statement) that will be evaluated each time. If the statement is true, the loop is repeated, else the loop stops, and the rest of the code is executed. The while-condition usually performs a logical operation to evaluate the value of the counter. An example of the while-condition is:
i<10
- In the example above, the condition written is i is less than 10, meaning the statement that will be repeated will be repated as long as i is less than 10.
- The <between-loops expression> is an expression that is executed each time before the <while-condition> is evaluated. The expression usually increments a number to the counter, so that when the while-condition is evaluated, it will return false after a certain number of loop-repititions. An example on that is:
i++
- In the example above, 1 is incremented to the variable i on each loop's beginning. After that, the condition will be evaluated and if it is true the loop continues.
[edit] Example
A full example on the code will be:
for(i=0;i<10;i++)
{
<perform expression>
}
The example above repeates the expression 10 times, because it:
- sets i to 0
- increments 1 to i before each loop
- evaluates if i is still less than 10 before each loop
IF (i) is still less than 10, the loop is again repeated. ELSE the loop stops.
[edit] Usage
The for loop is used to repeat something that its value is predefined. Meaning either a:
- number that is entered by the programmer
- or a variable that is set before the loop begins

