LOOPS STATEMENTS
CH#3
BS COMPUTER SCIENCE
UNIVERSITY OF SWAT
LOOPS
A statement or a set of statements that is
executed repeatedly is called loop.
Statements are executed for a specified no. of
time until the given condition remains true.
Three kinds
The “while” loop
The “for” loop
The “do-while” loop
The “while” loop
Conditional loop statement.
Used to execute statement(s) as long as the given
condition remains true.
Syntax:
while(condition)
{
statement(s);
}
If there is one statement than braces are not
used.
.“Condition” consists of a relational expression.
“Statements” represent the body of the loop.
The “do-while” loop
The “do-while” loop is also a conditional loop
statement.
Similar to while loop, but condition is tested
after executing the statement(s) of the loop.
Syntax:
do
{
statements;
}
while(condition);
do is a keyword of c++. Indicates the starting.
Statements represents the body of the loop.
Condition consists of a relational expression.
While vs. do-while loops
In while condition comes before the body of the
loop.
In do-while loop condition is tested after the
body of the loop.
The body of the do-while loop is executed at
least once either the condition is true or false.
The “continue” statement
The “continue” statement shifts the control
back to the beginning of the loop.
Used inside the body of the loop.
When executed control shifts to the first
statement of the body of the loop.
Syntax:
continue;
The “break” statement
The break statement terminates the execution
of the loop when executed inside the body of
the loop.
The “for” loop
The “for” loop statement is used to execute a
set of statements repeatedly for a fixed number
of times.
Also known as counter loop.
It has the following parts:
1.intialization 2.condition
3.increment or decrement
4 .body of the loop
:Syntax
for( initialization; condition;
increment/decrement)
E.g.,
for( int a=3,b=10; a<10; a++)
for( ; a<=10; a++)
The Nested Loops
A loop structure completely inside the body of
another loop structure is called nested loop.