Iterative structure: for
This structure allows the excution of a group of actions while a condition remains true, but includes also initialization and updating actions, ussually involving a control variable for the condition. It means that it allows the programmer to introduce an extra initialization action to be executed before entering the loop, and an extra updating action to be execute after each iteration. This makes this structure very suitable for situations where the number of iteration is known (for instance, traversing a linear structure or container, like a vector or an array)
The structure's beginning is marked with the keyword for. After that goes the initialization, the condition and the updating action, separed with semicolon (;) and surrounded by parenthesis. Then goes the action to be repeated on each iteration. The initialization can involve some variable declaration (whoose scope is only inside the loop). If the condition is false before getting into the loop, the actions inside it won't be executed. The updating statement is executed always at the end of an iteration and before evaluating the condition again.
Example: Calculating the average from an array A with N elements:
float sum = 0;
for (int i=0;i<N;i++) {
sum+=A[i];
}
float aver = sum/N;
The incializacion declares the variable i(counter) and set it to zero. Then, after each iteration, the updating increments that counter. The loop will run until i gets to N (when the condition i<N becomes false). It means that actions inside the structure will be executed for the following i values: 0,1,2,...,N-1. Outside the loop, the variable i will not exists anymore (if that variable is declared before the for and not in the initialization, when exiting the loop its value must be N).