You are on page 1of 39

Control Structure

(Repetition)

Control Structures
}

All programs can be written in terms of 3 control


structures
1.

Sequence Structure

2.

Selection Structure

3.

If (Single Selection Statement)

If-else (Double Selection Statement)

Switch (Multiple Selection Statement)

Repetition Structure

For

While

Do-while

Loops
}

Loop cause a section of your program to be repeated


certain number of times.

The repetition continues while a condition is true. When


condition becomes false, the loops ends and control
passes to the statements following the loop.

Types of Loops
}

for loop

while loop

do while loop

1. for Loop
}

for loop executes a section of code a fixed number of


times. Its usually used when you know, before entering
the loop, how many times you want to execute the code.

The for allows us to specify three things about a loop in a


single line.
a)

Setting a loop counter to an initial value.

b)

Testing the loop counter to determine whether


its value has reached the number of repetitions
desired.

c)

Increasing the value of loop counter each time


the program segment within the loop has been
executed.

for Loop
}

The general form of for statement is as under.


for ( initialization expression; test expression; increment/decrement
expression)
{
statement 1;
statement 2;
.
.
statement n;
}

for Loop Example


void main ( )
{
int j;
for ( j=0; j < 15; j++ )
cout<< j;
}

for Loop
}

The Initialization Expression


}

The Test Expression


}

The initialization expression is executed only once, when


the loop first starts. It gives the loop variable an initial
value.
The test expression usually involves a relational
operator. It is evaluated each time through the loop, just
before the body of the loop is executed. It determine
whether the loop will be executed again or not.

The Increment Expression


}

The increment expression changes the value of the loop


variable, often by incrementing it. It is always executed

Nesting of Loops
Loops can also be nested like if statements.
void main ( )
{
int r, c, sum;
for ( r = 1; r<= 3; r++)
{
for( c =1; c <= 2; c++)
{
sum = r + c;
cout<<r =<< r;
cout<< c =<< c;
cout<<sum =<<sum<<endl;
}
}
}

Output of Program

Variable Visibility
}

The loop body, which consists of braces delimiting


several statements, is called a block of code.

Variable defined inside the block is not visible


outside it.

Visible means that program statements can access


the variable.

Variable Visibility Example


void main ( )
{
for ( int i=0; i < 10; i++)
{
int j=i;
cout<< hello world<<j<<endl;
}
cout<< j;
undeclared.
}

//Error: j is undefined/

2. while Loop
}

The while statement, like if statement, test a


condition.

The syntax of while loop is


while ( expression )
{
statement 1;
statement 2;
}

while Loop Example


void main ( )
{
int n = 99;
while ( n != 0 )
{
cout<<Enter any number or 0 to quit the program;
cin >> n;
}
}

Tips
}

The statement within the while loop would keep on


getting executed till the condition being tested remains
true. When the condition becomes false, the control
passes to the first statement that follows the body of the
while loop.

The condition being tested may use relational or logical


operators as shown in the following example.
}

while ( i <= 10 )

while ( i <= 10 && j <= 15 )

while ( j > 10 && ( b < 15 || c < 20))

Tips
}

It is not necessary that a loop counter must be an int. It


can even be a float.
void main ( )
{
float a=10.0;
while ( a <= 10.5 )
{
cout<<a<<endl;
a = a + 0.1;
cout<<endl;
}
}

Output of Program

Counter-Controlled Repetition
}

Counter-controlled repetition
}

Definite repetition
}

Loop repeated until counter reaches certain value

Number of repetitions known

Example
A class of ten students took a quiz. The grades (integers
in the range 0 to 100) for this quiz are available to you.
Determine the class average on the quiz.

C++ code for this example


void main()
{
int total;
int gradeCounter;
int grade;
int average;
total = 0;
gradeCounter = 1;
while ( gradeCounter <= 10 ) {
cout << "Enter grade: ";
cin >> grade;

Contd
average = total / 10;
// display result
cout << "Class average is " << average << endl;
}

Output

Sentinel-Controlled Repetition
}

Suppose problem becomes:


Develop a class-averaging program that will process an
arbitrary number of grades each time the program is run
}

Unknown number of students

} How

end?

will program know when to

Contd
}

Sentinel value
}

Indicates end of data entry

Loop ends when sentinel input

Sentinel chosen so it cannot be confused with


regular input
}

-1 in this case

C++ code for this example


void main()
{
int total;
int gradeCounter;
int grade;
int average;
total = 0;
gradeCounter = 0;

// initialize total
// initialize loop counter

cout << "Enter grade, -1 to end: ";


cin >> grade;

Contd
// loop until sentinel value read from user
while ( grade != -1 )
{
total = total + grade;
gradeCounter = gradeCounter + 1;
cout << "Enter grade, -1 to end: ";
cin >> grade;
}

Contd
if ( gradeCounter != 0 )
{
average = total / gradeCounter;
cout << "Class average is " << average << endl;
}
else
cout << "No grades were entered" << endl;
}

//end main

Output

Exercise 1
Find the powers of 3 less than or equal to 100

1.

void main ( )
{
int product = 3;
while ( product <= 100)
{
cout<<"Product="<<product<<endl;
product = 3 * product;
}
}

Exercise 2
2.

calculates and prints the sum of the integers


from 1 to 10

void main ( )
{
int sum = 0, i;
while ( i <= 10)
{ sum=sum+i;
i++;
}
cout<<"sum="<<sum<<endl;
}

Task to be done
}

Print the table of a number entered by the user

}Typically,

for statements are used for countercontrolled repetition and while statements are used
for sentinel-controlled repetition.

for Repetition Structure


}

for loops can usually be rewritten as while loops


initialization;
while ( loopContinuationTest){
statement
increment;
}

Initialization and increment


}

For multiple variables, use comma-separated lists


for (int i = 0, j = 0;

j + i <= 10; j++, i++)

cout << j + i << endl;

}
32

Can have multiple initialization expressions, increment


expressions but only one test expression

3. do/while loop
}

Similar to while structure


}

Makes loop continuation test at end, not beginning

Loop body executes at least once

Format
do {
statement
} while ( condition );

33

Example Program
void main()
{
int counter = 1;

// initialize counter

do {
cout << counter << " "; // display counter
} while ( ++counter <= 10 ); // end do/while
cout << endl;
}

break Statement
}

break statement
}

Immediate exit from while, for, do/while, switch

Program continues with first statement after structure

Common uses
}

Escape early from a loop

Skip the remainder of switch

35

Example Program
void main() {
int x;
// loop 10 times
for ( x = 1; x <= 10; x++ )
{
if ( x == 5 )
break;
// break loop only if x is 5
cout << x << " "; // display value of x
} // end for
cout << "\nBroke out of loop when x became " << x
<< endl;
}

continue Statement
}

continue statement
}

Used in while, for, do/while

Skips remainder of loop body

Proceeds with next iteration of loop

while and do/while structure


}

Loop-continuation test evaluated immediately after the


continue statement

for structure
}

Increment expression executed

Next, loop-continuation test evaluated

37

Example Program
void main()
{
for ( int x = 1; x <= 10; x++ )
{
// if x is 5, continue with next iteration of loop
if ( x == 5 )
continue;
// skip remaining code in loop body
cout << x << " "; // display value of x
} // end for structure
cout << "\nUsed continue to skip printing the value
5"
<< endl;

Thank You

You might also like