C++ for loop
- for loop enables the user to execute a block of statement repeatedly until a certain condition gets false.
- for loop is suitable for the situations where we exactly know how many time we have to execute the statements within the body of loop.
- In for loop condition is always checked before the execution of the Loop-Body.
- It is also called as entry level looping statement because here condition is checked first then enters into the loop.
- The syntax of the for loop is as follows:
for(initialize counter;condition;increment/decrement counter)
- The initialize counter sets the initial value of loop-counter. This statement executes only once.
- The condition is an expression that determines the number of repetition of the Loop-body. The body of for loop will be executed as long as the condition is true. When the condition becomes false control of program exits from the loop-body and executes next statement present after the loop-body.
- The increment/decrement counter increments or decrements the value of loop-counter as per the need of program.
Here is a diagram which shows the concept of for loop:
Here is an example-program of for loop which prints the value from 1 to 5:
The output of the above program is as follows: