Sie sind auf Seite 1von 3

Loops

Loops repeat a statement a certain number of times, or while a condition is fulfilled.

Loop types:

Loop Type
while loop

Description
While a given expression is true it repeats the statement in the loop body. Before executing
the loop body, it tests the condition for true or false.

dowhile loop

It is like a while loop but it tests the condition after executing the loop body.
In above two loops we need to write the increment or decrement operation to break the loop

for loop

after sometime. But in for loop we have an option of incrementing or decrementing outside

for-each loop

This loop applies a function to the range of elements in a collection.

nested loops

When using one or more loops inside a loop is known as nested loop.

the loop body.

Loop Control Statements:


Control Statement
break statement
continue statement
goto statement

Description
Break terminates immediately the loop statement from executing further and execution
reaches just outside the loop body containing the break statement.
Continue statement is equivalent to going to the very end of the loop immediately by
skipping further statements.
It is equivalent to skipping the further statements and immediately jumping to the
labeled statement.

The WHILE loop


The while-loop simply repeats statement while expression is true. If, after any execution
of statement, expression is no longer true, the loop ends, and the program continues right after the
loop.
The while loop uses the following structure:
while (expression)
{
statement
}

Example:
while( a < 20 )
{
cout << "value of a: " << a << endl;
a++;
}
The DOWHILE loop

The do while loop is almost the same as the while loop. It behaves like a while-loop, except
that condition is evaluated after the execution of statement instead of before, guaranteeing at least
one execution of statement, even if condition is never fulfilled.
The Dowhile uses the following structure:
do
{
do something;
}
while (expression);
Example:
cin >> howmuch;
counter = 0;
do
{
counter++;
cout << counter << '\n';
}
while ( counter < howmuch);

The FOR loop


The for loop loops from one number to another number and increases by a specified value each
time.
The for loop uses the following structure:
for (Start value; end condition; increase value)
{
statement(s);
}
Example:
for (i = 0; i < 10; i++)
{
cout << "Hello" << "\n";
cout << "There" << "\n";
}

The NESTED FOR loop

The Nested for loop uses the following structure:


for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}

The NESTED WHILE loop


The Nested while loop uses the following structure:
while(condition)
{
while(condition)
{
statement(s);
}
statement(s);
}

The NESTED DOWHILE loop


The Nested dowhile loop uses the following structure:
do
{
statement(s);
do
{
statement(s);
}
while( condition );
}
while( condition );

Das könnte Ihnen auch gefallen