Advertise here.

Sunday 19 August 2012

C++ Programming Tutorial Lesson #4 - Loops


A loop lets you repeat lines of code as many times as you need instead of having to type out the code a whole lot of times.

For Loop

The for loop is used to repeat code a certain number of times between 2 numbers. You have to use a loop variable to go through each loop. The first part of a for loop initializes the loop variable to the number from which the loop starts. The second part is the condition that the loop must meet to exit the loop. The third part is used to increment the value of the loop variable. Here is an example of how to print the word Hello 10 times.
int x;
for (x = 1; x <= 10; x++)
   cout << "Hello\n";
The x++ part is something you haven't seen yet. Adding ++ to the front or back of a variable will increment it by 1. -- is used to decrement by 1. Putting the ++ before the variable increments it before the condition of the loop is tested and putting it after increments it after the loop condition is tested.
If you want to use more than one line of code in a loop then you must use curly brackets just like with an if statement.
int x;
for (x = 1; x <= 10; x++)
{
   cout << "Hello\n";
   cout << "There\n";
}

While Loop

The while loop repeats code until a condition is met. You don't have to use a loop variable but if you do then you need to initialize it before running the loop. You also need to increment the loop variable inside the loop.
int x = 1;
while (x <= 10)
{
   cout << "Hello\n";
   x = x + 1;
}

Do While Loop

The do while loop is like the while loop except that the condition is tested at the bottom of the loop.
int x = 1;
do
{
   cout << "Hello\n";
   x = x + 1;
}
while (x <= 10);

Break

The break command can be used to exit a loop at any time. Here is one of the above examples that will only print Hello once and then break out of the loop.
int x;
for (x = 1; x <= 10; x++)
{
   cout << "Hello\n";
   break;
}

Continue

The continue command lets you start the next iteration of the loop. The following example will not print Hello because the continue command goes back to the beginning of the loop each time.
int x;
for (x = 1; x <= 10; x++)
{
   continue;
   cout << "Hello\n";
}