It is a statement that is used to repeat set of statements up to a fixed number of times or until a given condition is satisfied.There are two types of loops:
- Conditional Loop (while and do-while Loop)
- Counter Loop (for loop)
It is a loop that executes a set of statements as long as a given condition remains true.Counter Loop
It is used to repeat a set of statements for a specified number of times.While Loop
It is used to repeat a set of statements until a given condition is satisfied.Syntax:
- When while statement is executed, the compiler checks the given condition written in parentheses.
- If the given condition is true then the statements enclosed in the braces ( body of loop) are executed.
- After the completion of first iteration control is shifted to while and the condition is again tested.
- This process is repeated until the condition is true.
- If the condition is false then control is transferred the statement that comes after the body of loop.
If the condition of loop never false then the loop never ends and called infinite loopNote: Infinite loop in useful where the programmer does not know in advance how many times the body of loop will be executed.
Loop control variable
A variable whose value control the number of iterations of loop is called loop control variable.
- Loop control variable always initialized before starting of the loop and incremented and decremented inside the loop body.
using namespace std;
while(a<=10) // Condition of loop
a++; // increment statement