Here's a simple example that helps explain the difference between the different loop types.
This simple for loop creates 5 stars. The first part of the for loop dictates the variable used to control the loop, in this case i. The second part says that the loop operates as long as i>0, and the third says to lower the value of i after each time the loop is executed. Note that the three parts are separated by semicolons, not commas.
1 2 3 4
|
int stars=5;
for (int i=stars;i>0;i--)
cout<<"*";
| |
The while loop and do/while loop are more similar to each other. This while loop does the same thing as the previous for loop, and continues to repeat as long as stars>0.
1 2 3 4 5 6 7
|
int stars=5;
while(stars>0)
{
cout<<"*";
stars--;
}
| |
Lastly, the do/while loop works the exact same as the while loop, except for the fact that the first time it will run
even when the condition specified is not true. The condition, in that case, only dictates when the loop should repeat.
1 2 3 4 5 6 7
|
int stars=5;
do
{
cout<<"*";
stars--;
} while (stars>0);
| |
All three loops shown here will result in the same behavior. Depending on what you are attempting, you may find it easier to use a particular type of loop in your program. It is fairly common to use loop types together, so for loops tend to use other for loops inside them, and while loops tend to use while loops inside them. Nested loops and the concept involved can seem confusing when trying to grasp the basics, but here's a simple example of the potential uses of double loops.
1 2 3 4 5 6 7 8 9 10 11 12
|
int stars=5;
//outer loop
for (int j=0;j<5;j++)
{
//inner loop
for (int i=stars;i>0;i--)
cout<<"*";
//outer loop commands
cout<<endl;
stars--;
}
| |
Here, you can see that the inner loop is used to output stars, while the outer loop is used to alter the quantity of stars and ensure the next execution of the loops occur on the next line.
Lastly, there's another couple important details about loops. You can set the condition used to control the loop to true or 1 to have it run no matter what.
1 2 3 4 5
|
while (true)
{
cout<<"*";
}
| |
Now, you would probably ask why anyone would want to do that, but there's another convenient feature; the ability to break out of the loop when desired. Here's a simple example so you can see how I broke out of the loop after ten stars.
1 2 3 4 5 6 7 8 9
|
int count=0;
while (true)
{
cout<<"*";
count++;
if (count==10)
break;
}
| |
There is more to learn, but this covers the basics and involves examples simple enough for a beginner to grasp. Hopefully it helps.