Let's see if I can explain effectively without being too wordy.
A loop is appropriate to use whenever you want to execute the same or very similar code more than once.
The simplest type of loop is the 'while' loop. The syntax is
1 2 3 4
|
while (condition)
{
//do stuff
}
|
At the start of the loop it checks if 'condition' is true. If it is true the code within the brackets is executed before coming back to check the condition again and starting over. If the condition is false the code in the brackets is skipped and the loop is over.
do while is very similar. The only difference is that the condition is checked at the end of the loop. This ensures that the code within the loop is always executed at least once. If the condition is true then the program goes back to the beginning of the loop.
1 2 3 4
|
do
{
//do stuff
} while (condition);
|
A for loop is a little bit more complex.
for (do this once at the beginning; condition; do this)
The first part of the for loop is executed only once before the loop starts. Before the code in the brackets is executed, the condition is checked. If it's true the code is executed, otherwise the loop breaks. The third part of the loop is executed at the end of every iteration. The loop:
1 2 3 4
|
for (int i = 0; i < n; i++)
{
//do stuff
}
|
...is actually the same as:
1 2 3 4 5 6 7 8
|
{
int i = 0;
while (i < n)
{
//do stuff
i++;
}
}
|
The keywords 'break' and 'continue' can respectively be used to break the loop immediately, or to skip the remaining code in the brackets and go back to the beginning of the loop.