Professional Documents
Culture Documents
Chapter # 06: Looping Structures
Chapter # 06: Looping Structures
Chapter # 06: Looping Structures
Looping Structures
Chapter Outline
Loops
‘while’ Loop
‘do while’ Loop
Pretest and posttest Loop
‘for’ Loop
Nested Loops
Loops
A type of control structure that repeats a statement or set of statements is known as looping
structure. It is also known as iterative or repetitive structure. In sequential structure, all
statements are executed once.
Loops are basically used for two purpose:
To execute a statement or number of statements for a specified number of times. E.g., a
user may display his name on screen for 10 times.
To use a sequence of values, e.g., a user may display a set of natural numbers from 1 to
10.
Types
There are three types of loops
While loop
Do while loop
For loop
Counter Controlled Loops
This type of loops depend upon the value of a variable known as a counter variable. The
value of counter variable is incremented or decremented each time the body of the loop is
executed.
This loop terminates when the value of counter variable reaches a particular value.
The number of iterations of counter-controlled loop is known in advance.
The iteration of this loop depends on the following:
Initial value of the counter variable.
Terminating condition.
Increment or decrement value
Sentinel Controlled Loops
This type of loop depends upon special value known as sentinel value. The loop terminates
when the sentinel value is encountered.
These types of loops are also known as conditional loops.
E.g., a loop may execute while the value of a variable is not -1. Here -1 is the sentinel value
that is used to terminate the loop.
The number of iterations of sentinel-controlled loop is unknown. It depends on the input
from the user. Suppose the sentinel value to terminate a loop is -1.
It the user enters -1 in first iteration, loop will execute only once. But if user enters -1 after
entering many other values, the number of iteration will vary accordingly.
A sentinel value is commonly used with while and do-while loops.
‘while’ Loop
While loop is the simplest loop of C++ language. This
loop executes one or more statements while the given
condition remains true. It is useful when the number of
iterations is not known in advance.
Syntax
while( condition )
{
statement 1;
statement 2;
;
;
Statement n;
}
#include <iostream.h>
#include <conio.h>
Pretest and
n =0;
while ( n==0) {
posttest in }
loop body
#include <iostream.h>
#include <conio.h>
main()
{
int n;
for(n = 1; n<= 5 ; n++)
cout<<n<<endl;
getche();
}
• The C++ continue statement is used to continue loop.
• It continues the current flow of the program and skips the
remaining code at specified condition.
Continue • In case of inner loop, it continues only inner loop.
Statement • Program
#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=10;i++){
if(i==5){
continue;
}
cout<<i<<"\n";
}
}
‘break’ Statement