This tutorial will show you how to use iteration in C++. We only cover iteration which most used in programming. We assume that you have already done the previous tutorial.
For Loop
The general format is :
for (initial condition; stopping condition; increment)
{
// write your code here
}
In your main function :
// main function
int main(int argc, char** argv)
{
int key;
// loop from i=0 until i<10 with increment i=i+1
for (int i=0; i<10; i++)
{
cout << “data number “ << i << “\n”;
}
cin >> key;
return 0;
}
The result is :
While Loop
The general format is :
// initialize stopping condition here;
while (stopping condition is false)
{
// write your code here
// if (condition met)
// stopping condition is true;
}
In your main function :
// main function
int main(int argc, char** argv)
{
int key;
// loop from i=0 until i<10
int i = 0; // initialize variable for stopping condition
while (i < 10) // i < 10 is the stopping condition
{
cout << “data number “ << i << “\n”;
i++; // increment i
}
cin >> key;
return 0;
}
The result is :