We have 3 types of loop in C++ : for loop, while loop and the do-while loop.
In the previous post, we had discussed the basics of the while and do-while loop. Now let us see what a ‘for loop‘ is and how it works.
Like all other loops, for loop also executes a statement or a group of statements repeatedly. Its syntax is:
for(initialization expression,test expression,increment expression) { statement(s); }
Initialization expression initializes a variable to be used in the loop.
Test expression tests value of a variable. Normally we use relational operators to specify test expressions.
Increment expression increases value of the test variable for each iteration of the loop.
Let us take an example to understand the working of the for loop.
Let us write a program to print numbers from 1 to 10 using for loop.
#include<iostream.h> #include<conio.h> void main() { clrscr(); for(int i=1;i<=10;i++) { cout<<i<<endl; } getch(); }
Here is the output: 1 2 3 4 5 6 7 8 9 10
Check out the real output on the screen below:
In the for loop used in the above example, int i=1 is the initialization expression.
i<=10 sets the test condition that the value of i should not be more than 10.
i++ is the increment expression which increments the value of i after each round of execution of the loop.
So initially we have i=1.
The test condition i<=10 evaluates true. So the for loop executes to print the value of ‘i‘ which is ‘1‘.
In the increment expression, value of ‘i‘ is incremented to ‘2’. Now we have i=2. The above step is executed again.
This is done till i=10 and ’10’ is printed. After this ‘i’ becomes 11. The test condition evaluates to false. And we exit the loop!
This is all how the ‘for loop‘ works. If you have any queries, do let us know!
super