1 min read
It is the iterative statement, through which we can execute a set of instructions repeatedly.
Syntax:-
for(initialization expression(s); test-expression;update-expression) { //Body of loop; }
Let’s understand all terms one by one:
- Initialization expression(s): It
initialize the loops control variable. It tells the compiler about the number of times the loop should work. It is executed once, atthe beginning of loop . - Test expression(s): It is basically a condition whose truth value decides whether the loop body will execute in the
next turn or not. If its value is true, theloop will continue,otherwise , it is terminated. - Update expression(s): It changes the value of the loops variable.
- Body of the loop: the statements that you want to execute repeatedly are placed in this.
Example:
//program to print numbers from 1 to 10 int main() { int I; for(i=0;i<=10;++i) //no semicolon is needed here cout<<i<<"\n"; return 0; }
OUTPUT
1 2 3 4 5 6 7 8 9 10
EXPLANATION:
- Firstly initialization expression is evaluated(i=1) which gives initial value to the
variable i. - Then test expression is evaluated (i<=10) which results into true I.e, (1<10).
- Since test expression is true body is executed(cout<<i)which prints 1 to the screen.
- Then
updat e takes place(++i) i is incremented, now the value ofi becomes 2, which further goes to test expression and evaluate the condition(2<10) true,body will be executed. - Loop continues in this way,till the(i<=10) is true. At (i=11), condition is false and loop terminates.
You must be logged in to post a comment.