0% found this document useful (0 votes)
10 views

Week 05

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Week 05

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

CE-116

COMPUTER PROGRAMMING
Muzammil Ahmad Khan
[email protected]

Computer Engineering Department


WEEK NO:05

Loop Mechanism

2
Objectives

• To apply the same steps again and again to a block of


statements.

• Recall a block of statement is one or more statement, block


usually defined by braces { … } with syntactically correct
statements inside.

3
Objectives

In this chapter you will:


• Learn about repetition (looping) control structures
• Explore how to construct and use count-controlled, sentinel-
controlled, flag-controlled, and EOF-controlled repetition
structures
• Examine break and continue statements
• Discover how to form and use nested control structures

4
Why Is Repetition Needed?

• Repetition allows you to efficiently use variables


• Can input, add, and average multiple numbers using a
limited number of variables
• For example, to add five numbers:
− Declare a variable for each number, input the numbers and
add the variables together
− Create a loop that reads a number into a variable and adds
it to a variable that contains the sum of the numbers
5
Most Common Uses of Loops
You should master all these!
• For counting
• For accumulating, i.e. summing
• For searching
• For sorting
• For displaying tables
• For data entry – from files and users
• For menu processing
• For list processing
6
Designing a loop

• It take programming skill to design a good loop. There are several


questions you should answer to guide you in this process.
• Questions which should be asked when designing any loop
structure
i. What is the condition that ends the loop?
In most cases this is straight forward, but make sure you know
exactly what that condition is and make sure it can occur.
ii. How should the condition be initialized?
Make sure the loop control variable is appropriately initialized so the
loop doesn't terminate immediate before doing anything. If you fail to
properly initialize the pre-conditions before starting a loop the results
can be undefined.
7
Designing a loop

iii. How should the condition be updated?


Is this taken care of automatically by comparing input values to a
sentinel value, or do you have to increment a counter, check a flag,
etc.
iv. What is the process being repeated?
What action is coded inside the loop to be repeated?
v. How should the process be initialized?
Are there any variables, etc. that need to be initialized in addition to
the loop control variable before starting the loop? For example, if
summing a list of values, you need to initialize sum to zero. This is
not done automatically when you create the variable.
8
Designing a loop

iii. How should the condition be updated?


Is this taken care of automatically by comparing input values to a
sentinel value, or do you have to increment a counter, check a flag,
etc.
iv. What is the process being repeated?
What action is coded inside the loop to be repeated?
v. How should the process be initialized?
Are there any variables, etc. that need to be initialized in addition to
the loop control variable before starting the loop? For example, if
summing a list of values, you need to initialize sum to zero. This is
not done automatically when you create the variable.
9
Designing a loop

vi. How should the process be updated?


What processes are executed inside the loop? For example, in
summing a list of values: (1) get the next value, (2) add it to the
running sum.
vii. What is the state of the program on exiting the loop?
If there anything you need to do to clean up, like closing files
that were used in the loop, or outputting values calculated in the
loop?

10
The while Loop

• The general form of the while statement is:


while (expression)
statement
while is a reserved word
• Statement can be simple or compound
• Expression acts as a decision maker and is usually a logical
expression
• Statement is called the body of the loop
• The parentheses are part of the syntax
11
The while Loop

• Expression provides an entry condition

• Statement executes if the expression initially evaluates to true

• Loop condition is then reevaluated

• Statement continues to execute until the expression is no longer true

• Infinite loop: continues to execute endlessly

• Can be avoided by including statements in the loop body that assure


exit condition will eventually be false
12
The while Loop

13
The while Loop

14
Counter-Controlled while Loops

• A counter controlled loop is also known as definite


repetition loop, since the number of iterations is known
before the loop begins to execute. The counter-controlled
loop has the following components:
• a control variable.
• the increment (or decrement)value by which the control
variable is modified at each iteration of the loop.

15
Counter-Controlled while Loops

• the loop terminating condition that checks if looping should


continue.
• Since the counter-controlled loop is controlled by a counter
value, at each iteration counter value will increase or
decrease with a definite value and condition will be
checked, so the number of loop execution becomes
definite. Any task involving definite iteration can be solved
using a counter-controlled loop.

16
Counter-Controlled while Loops

• If you know exactly how many pieces of data need to be read, the
while loop becomes a counter-controlled loop

17
Counter-Controlled while Loops

• In this example, while loop increments the value of i by three every iteration.
The loop terminates when the value of i exceeds 12.

#include <iostream>
using namespace std;
int main() {
int i=0;
while (i<=12)
{
cout<<i<<"\t";
i += 3; }
cout<<endl;
}
18
Sentinel-Controlled while Loops

• A sentinel-controlled loop is also called an indefinite


repetition loop because the number of iterations is not
known before the loop starts executing. In a sentinel-
controlled loop, a special value called sentinel value is used
to change the loop control expression from true to false in
order to determine whether to execute the loop body.
Sentinel controlled loop is useful when we don’t know in
advance how many times the loop will be executed.

19
Sentinel-Controlled while Loops

• Sentinel variable is tested in the condition and loop ends when


sentinel is encountered.

20
Sentinel-Controlled while Loops

• In this example the sentinel value is set to 7. Therefore, the


• The main difference
loop keeps repeating until the user input 7.
between Sentinel and Counter
#include <iostream>
Controlled Loop in C ++ is that
using namespace std;
const int sentinelVal = 7; in a Sentinel Controlled Loop,
int main ()
{ exactly how many times loop
int x; body will be executed is not
while (x !=sentinelVal)
{ known and, in a Counter,
cout<<x<<endl;
Controlled Loop, how many
cout<<"Input x:";
cin>> x; times loop body will be executed
}
} is known.

21
Flag-Controlled while Loops

• A flag-controlled while loop uses a bool variable to control the loop


• The flag-controlled while loop takes the form:

22
Flag-Controlled while Loops

• A bool variable is defined and initialized to serve as a flag.


The while loop continues until the flag variable value flips
(true becomes false or false becomes true). In the following
example the user is asked to enter numbers at the
keyboard which are added together. To stop the addition
the user enters a negative number.
23
Flag-Controlled while Loops
#include <iostream>
• In the following
using namespace std;
example, the flag
int main (){
found is set to false
int x;
at the beginning. In
x = 5;
each iteration value
bool found;
of x is incremented
found = false;
by 5. When the
while (found==false){
value of x exceeds
x += 5;
20, the flag is set to
if (x>20)
true, and the loop
found = true;
terminates
else
cout<<x<<endl;
} }
24
The for Loop

• The general form of the for


statement is:
for (initial statement;
loop condition; update
statement)
statement

• The initial statement, loop


condition, and update statement
are called for loop control
statements

25
The for Loop

The for loop executes as follows:


1. The initial statement executes.
2. The loop condition is evaluated. If the loop condition evaluates to true
i. Execute the for loop statement.
ii. Execute the update statement (the third expression in the
parentheses).
3.Repeat Step 2 until the loop condition evaluates to false.

The initial statement usually initializes a variable (called the for loop control, or for
indexed, variable).
In C++, for is a reserved word.
26
The for Loop

27
The for Loop

28
The for Loop (comments)

The following are some comments on for loops:


• If the loop condition is initially false, the loop body does not execute.
• The update expression, when executed, changes the value of the
loop control variable (initialized by the initial expression), which
eventually sets the value of the loop condition to false. The for-loop
body executes indefinitely if the loop condition is always true.
• C++ allows you to use fractional values for loop control variables of
the double type (or any real data type). Because different computers
can give these loop control variables different results, you should
avoid using such variables.

29
The for Loop (comments)

• A semicolon at the end of the for statement (just before the


body of the loop) is a semantic error. In this case, the action of
the for loop is empty.
• In the for statement, if the loop condition is omitted, it is
assumed to be true.
• In a for statement, you can omit all three statements—initial
statement, loop condition, and update statement. The following
is a legal for loop:
• for (;;)
cout << "Hello" << endl;

30
The for Loop (comments)

• A semicolon at the end of the for statement (just before the


body of the loop) is a semantic error. In this case, the action of
the for loop is empty.
• In the for statement, if the loop condition is omitted, it is
assumed to be true.
• In a for statement, you can omit all three statements—initial
statement, loop condition, and update statement. The following
is a legal for loop:
• for (;;)
cout << "Hello" << endl;

31
The for Loop (comments)

32
The do…while Loop

• The general form of a do...while statement is:


do
statement
while (expression);
• The statement executes first, and then the expression is evaluated
• If the expression evaluates to true, the statement executes again
• As long as the expression in a do...while statement is true, the
statement executes

33
The do…while Loop

• To avoid an infinite loop, the loop body must contain a


statement that makes the expression false
• The statement can be simple or compound
• If compound, it must be in braces
• do...while loop has an exit condition and always iterates
at least once (unlike for and while)

34
The do…while Loop

• To avoid an infinite loop, the loop


body must contain a statement
that makes the expression false
• The statement can be simple or
compound
• If compound, it must be in braces
• do...while loop has an exit
condition and always iterates at
least once (unlike for and
while)
35
The do…while Loop

36
break & continue Statements

• break and continue alter the flow of control


• When the break statement executes in a repetition structure, it
immediately exits
• The break statement, in a switch structure, provides an
immediate exit
• The break statement can be used in while, for, and do...while
loops

37
break & continue Statements

• The break statement is used for two purposes:


1. To exit early from a loop
2. To skip the remainder of the switch structure
• After the break statement executes, the program
continues with the first statement after the structure
• The use of a break statement in a loop can eliminate
the use of certain (flag) variables

38
break & continue Statements

• continue is used in while, for, and do…while structures


• When executed in a loop
− It skips remaining statements and proceeds with the next iteration of the
loop
• In a while and do…while structure
− Expression (loop-continue test) is evaluated immediately after the continue
statement
• In a for structure, the update statement is executed after the continue
statement
− Then the loop condition executes
39
Nested Control Structures

• Suppose we want to create the following pattern


*
**
***
****
*****
• In the first line, we want to print one star, in the second line
two stars and so on

40
Nested Control Structures

• Since five lines are to be printed, • The syntax is:


we start with the following for
statement for (i = 1; i <= 5 ; i++)
for (i = 1; i <= 5 ; i++) {
• The value of i in the first for (j = 1; j <= i; j++)
iteration is 1, in the second
iteration it is 2, and so on cout << "*";
• Can use the value of i as limit cout << endl;
condition in another for loop
nested within this loop to control }
the number of starts in a line
41
Nested Control Structures

• What pattern does the code produce if we replace the first for statement with
the following?

for (i = 5; i >= 1; i--)

• Answer:
*****
****
***
**
*
42
Summary

• C++ has three looping (repetition) structures: while, for, and


do…while
• while, for, and do are reserved words
• while and for loops are called pre-test loops
• do...while loop is called a post-test loop
• while and for may not execute at all, but do...while always
executes at least once

43
Summary

• while: expression is the decision maker, and the statement is


the body of the loop

• In a counter-controlled while loop,


− Initialize counter before loop

− Body must contain a statement that changes the value of the counter variable

• A sentinel-controlled while loop uses a sentinel to control the


while loop
44
Summary

• for loop: simplifies the writing of a count-controlled while


loop
• Executing a break statement in the body of a loop
immediately terminates the loop
• Executing a continue statement in the body of a loop skips
to the next iteration
• After a continue statement executes in a for loop, the
update statement is the next statement executed
45

You might also like