Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 26

Chapter 4

Loop Structure
Objectives:

• Loop structure
• While, for, and do/while loop structures
• Nested loops
• Exercises

Fall 2009, Mohamad Eid GNG1106


Loop Structures

 Most algorithms require repetition structures in order to execute


one or more instructions a certain number of times.
 A loop can be:
– a definite repetition loop if we know in advance the number of
repetitions, or
– an indefinite repetition loop if we do not know in advance the
number of repetitions.
 The number of repetitions,
– in a definite repetition loop is controlled by a counter (usually
an integer variable),
– whereas the number of repetitions in an indefinite repetition
loop is controlled by a sentinel (usually an integer variable).
Loop structure expressed in pseudo-code
 A logical expression is evaluated repeatedly and as long as the logical
expression is TRUE, an instruction bloc is executed.
Repeat while logical_expression
Instruction bloc that is executed while logical_expression is TRUE
OR
Repeat
Instruction bloc that is executed while logical_expression is TRUE
While logical_expression
– In pseudo-code, all instructions at the same level of indentation constitutes
an instruction bloc
– Important: the instruction bloc must modify one or more variables in the
logical_expresssion. If not, what will be the consequence?
 Nested loop structures
– The loop structure is considered a single instruction
– So it is possible to include another loop structure as part of the set of
instructions within a loop structure
Example of the definite repetition loop

Program Memory Working


Memory
Assign 1 to ctr
Repeat while ctr is less than or ctr
equal to 10
Print “Iteration number “, ctr
Increment ctr
Print “ctr upon exit of the loop: ”,
ctr

CPU
Example of the indefinite repetition loop

Program Memory Working


Memory
Assign 1 to sentinel
Repeat while sentinel not equal to sentinel
0
Print “Enter 0 (zero) to exit the
loop”
Read value into sentinel
Print “We are out”

CPU
Example of the indefinite repetition loop
 What are the differences with the first version?

Program Memory Working


Memory
Repeat
Print “Enter 0 (zero) to exit sentinel
the loop”
Read value into sentinel
while sentinel not equal to 0
Print “We are out”

CPU
Example of a nested loop

Program Memory
Print “Enter an integer”
Read value into num Working
Repeat while num not equal to -1 Memory
Assign 1 to factorial
Assign num to ctr num
Repeat while ctr larger or equal to 1
Assign factorial*ctr to factorial factorial
Decrement ctr
Print “The factorial of “, num, “is ”,
factorial
Print “Enter an integer”
Read value into num
Print “You have chosen to quit”
CPU
Loop Structures in C

 There exists in C three repetition structures:


– the while structure,
– the do/while structure, and
– the for structure.
while Repetition Structure
 Allows the execution of one or more C commands while a logical expression
remains true.

 Syntax for repeating a single C command:


while (logical expression) Careful: there is no ; here.
command; The C command directly below
the while () is executed as
 Syntax for repeating multiple C commands: long as logical
while (logical expression) expression
{ remains true.
command 1;
command 2; The C commands delimited by a
 pair of {} directly below the
command n; while () are executed as long
} as logical expression
remains true.
 The while structure is a pre-tested loop.
 It is possible that the commands in the loop are never executed.
 Flowchart of the while structure for repeating a single command:

True
Expression command;
?

False
Components of a Loop
• Initial value of counter
• Condition (defines the final value)
• Body of statements
• Increment/decrement counter

int counter = 1;

While(counter<5)
{
printf(“%d\n”, counter);
counter++;
}
 A definite while loop is controlled by a counter; the following are required if a
definite loop is to execute correctly:
– initialization of the counter before the loop,
– a command in the loop that modifies the value of the counter,
– a logical condition that tests the value of the counter against its expected
final value such that the logical expression evaluates to false and
the loop is exited.
 An indefinite while loop is controlled by a sentinel; the following are required
if an indefinite loop is to execute correctly:
– initialization of the sentinel before the loop,
– a command in the loop that modifies the sentinel,
– a logical condition on the sentinel that eventually causes the logical
expression to evaluate to false in order to exit the loop.
 It is very good practice to indent the instructions in the instruction block of a
while loop in order to help visualize the structure of the program. Using {} to
include a single command in a while loop is possible and can also help clarify
the code.
 Example of a definite repetition loop using the while structure:
int ctr;
ctr = 1;
while (ctr <= 10)
{
printf(“Iteration number: %d\n”, ctr);
ctr++;
}

 Example of an indefinite repetition loop using the while structure:


int sentinel;
sentinel = 1;
while (sentinel != -1)
{
printf(“Enter -1 to exit the loop\n”);
scanf(“%d”, &sentinel);
}
do/while Repetition Structure
 The do/while repetition structure is similar to the while structure
except that it is a post-tested loop.
 The commands in the loop are always executed at least once.

 Syntax for repeating a single C command:


Careful: there is no ; here.
do
command; The C command between the do
while (logical expression); and while () is repeated as
long as logical
 Syntax for repeating many C commands: expression
do remains true.
{
The C commands delimited by a
command 1;
pair of {} between the do and
command 2;
while () are repeated as long
 as logical expression
command n; remains true.
}
while (logical expression); Careful: there is a ; here.
 Flowchart of the do/while structure for repeating a
single command:

do

command;

True
while( )

False
 Operation of a do/while structure in a program:
 
do Program execution flows into the
do/while structure, performing
{ at least once the commands
command 1; between the {}. The logical
command 2; expression is then tested and if
true, execution returns to the do
} statement and the commands
True while (logical expression); between the {} are repeated.
  When logical expression
False becomes false, program execution
continues after the while ();

 The commands in a do/while structure must modify at least one variable in


the logical expression; otherwise, an infinite loop results.

 It is possible to break out of an infinite do/while loop in the same manner as


in the case of an infinite while loop.
 A definite do/while loop is controlled by a counter; the following are required
if a definite loop is to execute correctly:
– initialization of the counter before or during the first pass through the loop,
– a command in the loop that modifies the value of the counter,
– a logical condition that tests the value of the counter against its expected final
value such that the logical expression evaluates to false and the loop
is exited.

 An indefinite do/while loop is controlled by a sentinel; the following are


required if an indefinite loop is to execute correctly:
– initialization of the sentinel before or during the first pass through the loop,
– a command in the loop that modifies the sentinel,
– a logical condition on the sentinel that eventually causes the logical
expression to evaluate to false in order to exit the loop.

 It is very good practice to indent the instructions in the instruction block of the
loop in order to help visualize the structure of the program. Using {} to include a
single command in a do/while loop is possible and can also help clarify the
code.
 Example of a definite repetition loop using the do/while structure:
int ctr;
ctr = 1;
do
{
printf(“Iteration %d\n”, ctr);
ctr++;
}
while (ctr <= 10);

 Example of an indefinite repetition loop using the do/while structure:


int sentinel;
sentinel = 1;
do
{
printf(“Enter -1 to exit the loop\n”);
scanf(“%d”, &sentinel);
}
while (sentinel != -1);
for Repetition Structure
 The for looping structure is a definite repetition structure that makes use of a
counter.
Careful: there is no ; here.
 Syntax to repeat a single C command:
for (expression 1; expression 2; expression 3)
command;
 Syntax to repeat a multiple C commands:
for (expression 1; expression 2; expression 3)
{ Careful: there are ; here.
command 1;
command 2;

command n;
}
 The three expressions in the for loop have the following role:
– expression 1 is an arithmetic expression that initializes the counter,
– expression 2 is a logical expression that tests the counter against its final value,
– expression 3 is an arithmetic expression that modifies the value of the counter.
 Flowchart of the for repetition structure for repeating a single
command:

Counter
expression 1;
Initialization

True
expr. 2; command; expression 3;
Logical
expression that Counter
tests the counter Modification
False
against its final
value
 Operation of a for structure in a program:
 
 
for (initial value; condition; increment/decrement)
{
command 1;
command 2;
}
 
A Program execution flows first into initial value which is evaluated once to
initialize the loop counter.
B condition is then evaluated; recall that it is a logical expression containing the
loop counter;
D if condition evaluates to false, then the commands between the {} are skipped
and the program continues to execute after the loop;
E if condition evaluates to true, then the commands between the {} are executed
and increment/decrement is performed to modify the value of the counter;
F back to step B.
 The for structure is a pre-tested loop.
 It is possible that the commands in the loop are never executed.

 It is very good practice to indent a for loop and the commands in


the loop in order to help visualize the structure of the program.
Using {} to include a single command in a for loop is possible and
can also help clarify the code.

 Example of a repetition loop using a for structure:


int ctr;
for (ctr=1; ctr<=10; ctr++)
printf(“Iteration %d\n”, ctr);
Example

 Writea program that prints all numbers from 10 to


50 inclusively and on separate lines
On the Use of Real Variables as Loop Counters
 It is possible to use a real variable as a counter to control looping in a definite repetition
loop.

 In theory, real variables can be tested for equality against a given value but in practice this
is not robust due to the imprecise nature of arithmetic with real variables on computers.

 It is best to modify the logical expression for the loop termination condition such that
testing for equality is not required.
– Looping from 1.0 to 2.5 inclusively might be coded as:
float start=1.0, end=2.5, inc=0.5, ctr;
 
for (ctr=start; ctr <= end; ctr=ctr+inc)
printf(“Value of ctr: %f\n”, ctr);
– The above loop is best implemented as:
 
Robust! for (ctr=start; ctr < (end+0.5*inc); ctr=ctr+inc)
printf(“Value of ctr: %f\n”, ctr);
Nested Loops
 Any C command can be placed inside any of our repetition structures;
this includes decision structures and other loops. Loops placed inside
of loops are called nested loops.

 Example:
int x,y,
for(x = 1; x < 3; x++)
{
for(y = 1; y < 4; y++)
{
printf(“sume = %f\n”, x+y);
}
}
 Note how indentation and {} helps to clear up the programmer’s
intentions.
Thank You!

‫متشکرم‬

Fall 2009, Mohamad Eid GNG1106

You might also like