for loop is widely used loop in programming language.
It also works like the while loop as we seen in previous tutorial.
for loop contains mainly 3 expressions.
The first expression is treated as statement and executed, then second expression is condition which is evaluated and checked to execute body of loop. At last third expression is increment or decrement which is performed after every iteration.
For loop syntax
123456789101112131415 | for(expression 1; expression 2; expression 3){//Statement 1// Statement 2..//Statement n} |
In above syntax we can we for loop having 3 expressions and block of statement in curly braces.
Example
123 | for(int s=1;s<3;s++)cout<<“s=”<<s; |
In above example we written for loop with expression 1 s=1 expression 2 s<3 and expression 3 s++.for loop iterated for 2 time and prints output as s=1 ,s=2.
Program to demonstrate for loop in c++
12345678910111213141516171819202122232425 | #include<iostream.h>void main (){int i;cout << ” for loop execution “;for(i = 0 ; i < 5; i ++){cout << “technical seek”;cout << “\n “;}cout<<“for loop executed “;getch();} |
Output:-
for loop execution
technical seek
technical seek
technical seek
technical seek
technical seek
for loop executed
Program description
- In above program we demonstrate for loop .
- First we take variable declare the variable I.
- Next we write for loop with 3 expressions. First is i = 0 which initialize i value . Then second expression condition i < 5 .
- Now condition is checked i = 0 < 5 , this condition is true so statement in for loop executed
- Now flow goes to increment expression i ++ . Value of i is incremented now i = 1
- Next condition is checked i=1 < 5 , condition true again statement executed.
- Similarly , loop iterated till value of i = 5
- In this case i=5 , condition false so execution comes out of the loop and rest of code executed.