For Loop Statement - Control Structures

How is a For Loop Statement used in C++?
What is iteration?

Explanation

The For Loop Statement is an iteration statement that executes a set of code repeatedly, given the initial value, the condition,increment value.

Syntax:


for(initialization; condition; increment)

Example :



#include <iostream.h>
using namespace std;
int main(void)
{
int i;
for(i= 0;i<5;i++)
{
cout << "for loop has looped:: " << i << " ::times" << endl;
}
}

Result :

for loop has looped:: 0 ::times
for loop has looped:: 1 ::times
for loop has looped:: 2 ::times
for loop has looped:: 4 ::times

In the above example the "for" statement iterates starting with the value of i=0 till i is less than 5 everytime increasing the value of i by 1.

Example :



#include <iostream.h>
using namespace std;
int main(void)
{
int i=0;
int j=0;
for(;i<5;i++)
{
cout << "Value of j is:: " << j++ << endl;
}
}

Result :

Value of j is:: 0
Value of j is:: 1
Value of j is:: 2
Value of j is:: 3
Value of j is:: 4

In the above example, since the value of "i" is initialized before, the initialization value of the for loop is left blank. This is another way of declaring the for loop statement. This is iteration in C++.

C++ Tutorial


Ask Questions

Ask Question