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)

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.

void main()
 for(int i=1;i<=10;i++)
  { cout<<i<<endl;
 Here is the output:

Check out the real output on the screen below:

Basics of  FOR loop in C++ for CBSE class 11

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!


Founder & Senior Editor of ChewCode.com and Editor at GizmoBolt.com. Sakshi is currently pursuing MCA. She is a foodie and has a unique love for learning computer programming languages. Follow her on Google + | Facebook | Twitter. Contact her at [email protected] for feedback and sending tips.

Tags: , , , ,

1 Comment on this article. Feel free to join this conversation.

  1. ghhuu February 2, 2018 at 10:38 am - Reply


Leave A Response