Loops

You might also like

Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 2

For Loop

The for loop is used to repeat code a certain number of times between 2 numbers. Yo
u have to use a loop variable to go through each loop. The first part of a for loop initia
lizes the loop variable to the number from which the loop starts. The second part is th
e condition that the loop must meet to exit the loop. The third part is used to increme
nt the value of the loop variable. Here is an example of how to print the word Hello 1
0 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 th
e variable increments it before the condition of the loop is tested and putting it after i
ncrements 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 brack
ets 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 vari
able 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 botto
m 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 exa
mple 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";
}

You might also like