You are on page 1of 13

Looping

To execute a group of statements more than


once, C++ provides the while, do while
and for statements for performing
repetitive tasks.
The while Loop Statement

Repeatedly executes a statement if


a certain condition is true.
It is a pretest loop
The while Loop Statement
The do… while Loop Statement

There are cases where we may want to


execute the body of the loop at least
once before testing the condition. In
other words, there are times where we
may need a posttest loop. This is where
the do … while loop comes in.
The do… while Loop Statement
The for Loop Statement

The for loop is ideal for working with counters


because it provides built-in expressions that
initialize and update variables.
It’s a pretest loop.
The for Loop Statement
The for Loop Statement
The continue and break
Statements
The break statement can also be placed inside a
loop. When it is encountered, the loop stops
and program jumps to the statement following
the loop.
The continue and break
Statements
The continue statement, placed inside a loop,
causes the loop to stop its current iteration and
begin the next one. All statements in the body
of the loop that come after it are ignored.
Choosing a Loop…

The while loop is ideal for situations where a


pretest loop is required, i.e., if you don‘t want to
iterate if the condition is false from the beginning.
The do...while loop is ideal for situations where a
posttest loop is required, i.e., if you want the loop
to iterate at least once even if the condition is false
from the beginning.
The for loop is ideal for situations where a counter
variable is needed.
Variable Scope
Normally, we expect a variable name to be a unique
entity.
However, C++ allows us to reuse a name as long as it is
used in different contexts. This context is known as a
scope.
A scope is a region of the program and a name can
refer to different entities in different scopes.
Most scopes in C++ are delimited by curly braces.
Names are visible from their point of declaration until
the end of the scope in which the declaration appears.
Variable Scope

You might also like