A ‘for’ loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times.
The syntax of a for loop in C++ is:
for (initialization; condition; increment/decrement)
The working of a ‘for’ loop:
1. The initialization step is executed first, and only once in the beginning. It is used to declare and initialize any loop control variables.
2. Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.
3. After the body of the ‘for’ loop executes, the flow of control jumps back up to the increment/ decrement statement and updates any loop control variables.
4. Then condition is evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again condition). After the condition becomes false, the for loop terminates.
int main ()
\\ for loop execution
for(int a = 10;a<20;a = a + 1)
count<<"value of a:"<<a>>endl;//
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15