The for loop is the easiest loop in C++ to understand. All elements
of this loop are in one place contrary to those remaining two (while, do-while)
whose elements are scattered in the program.
For loop executes a section of for a certain number of times.
Syntax
for(initialization; condition; increment)
{
Statements(s);
}
How this
loop works is explained below:
Initialization: This is the very first part of for
loop, here you can initialize the counter variable (variable of loop) e.g. i=1
or i=0. But this part is executed only once. This is to initialize the loop.
Condition: This the second part of for loop and
the most important part, this part decides how many times the loop has to be
executed.
If the condition is true the loop’s body is executed else it
jumps to next statements.
Increment: if the condition is true there is an
increment in the counter variable. The increment is done using increment
operator “ ++ ”.
You can increment in different ways for example:
i++ //post
increment
++i //pre increment
1+i
i+1
You can also increment for two or three times, it’s up to you that how many times you want, you
can do this too
i+3
or i+4
After the increment the condition is evaluated again leaving
the first pat this time, if the condition is true the loop executes further
else it is terminated and jumps to the next statements
Here is flow diagram of control
Example:
#include
<iostream>
using namespace std;
int main(){
int x;
for(i=0;i<=10;i++) //the for loop, loop
continues for 10 times
{
cout << “The squre is” << i*i << endl; // pints the square of i
}
return 0;
}
The output
of the following program is
0 1 4
9 16 25 36 49
64 81 100
This program has printed squares of numbers starting from 1
to 10. We only need to specify the one statement.
Post a Comment