ITERATION: WHILE LOOPS
LESSON OBJECTIVES
At the end of the lesson students
should be able to:
● explain the concept of while
loops within two minutes without
the use of reference.
● reproduce the while loop
syntax/structure in a given
algorithm correctly without the
assistance of the teacher
● create flowcharts to show the
flow of logic for the while loop,
based on the given problem
statement.
● represent a while loop structure
TYPES OF LOOP
There are three main types of loops (for,
while and repeat-until) which falls under
the following categories:
❏Counter Controlled
❏Condition Controlled
Each type of loop works in a slightly different
way and produces different results.
Our focus for this activity is to understand the
while loop and how it executes instructions.
ACTIVITY
You will complete the following activity below by
selecting the link that will take you to the
studio.code.org workspace.
As per the previous video you will see how the
while loop structure functions differently from the
for loop as you manipulate the farmer in levels 1
TYPES OF LOOP
A for loop is a repetition control structure that
allows you to efficiently write a loop that needs to
execute a specific number of times.
As stated in our previous lesson, one of the main
feature of the for loop is that it is counter-
controlled. Hence the count variable e.g. count will
be updated inside the loop block for each iteration
until it reaches the known terminating value.
The for loop syntax - the repetitive statement - is
written with the loop’s control variable being
initialized to 1 (starting value) and then the range
with the ending value e.g. ..to 10
ACTIVITY
Identify one feature of the while loop that makes it
different from the for loop. Write a sample of how
the while loop syntax is represented in
pseudocode.
UNDERSTANDING THE
WHILE LOOP
A while loop structure unlike the for loop is utilized when
the number of iterations to execute a set of instructions
are unknown to the programmer.
In a situation like this, the programmer will have to
determine a condition that will cause the loop to
eventually terminate.
Problem Statement:
You are to take the bus to school but you have to walk to
the bus stop.
How many steps will it take to get to the bus stop? You
are unsure and you cannot walk indefinitely.
So what do you think would be an appropriate condition
to ensure you only walk till you get to your destination?
a. While (not at bus stop) do
walk
b. While (you are at bus stop) do
walk
c. While (you are at home) do
WHILE Loops
The “While” loop is an indefinite loop, also known as the
pre-test loop. The pre-test is used to get from the user an
initial value for the loop’s variable. The conditional
expression inside the repetitive statement is evaluated
based on the pre-test and if true the loop block
statements execute.
The post-test is used update the value of our loop
variable. The conditional expression is then re-evaluated
against that new value from the post-test and, if it is still
true, the loop block statements execute again. The
repetition of the loop block is terminated when the
conditional expression becomes false.
How can the following problem statement be represented
using the while loop syntax? Problem Statement: You want
to fill a bottle with juice.
What would be a possible pre-test and post test that could
be added to the syntax above?
WHILE LOOPS
The while loop can be thought of as a
repeating if statement as the block of
instructions are executed repeatedly
based on a given (True) condition.
The condition that causes the loop to
stop must be a logical (yes/no) test.
The test will evaluate a value typically
from a prior user input which is
evaluated using a relational operator
such as >, < or =.
ACTIVITY
Explain a scenario which would
involve using a while loop as
THE WHILE LOOP Consider this simple algorithm for
entering a correct password:
SYNTAX
The flowchart indicated on this slide shows you an example of
what a conditioned control loop will look like. The structure of
enter password
the while loop in pseudocode is as follows:
unless password <> “Sesame”, go
pretest
While test back to step 2
Commands say ‘Password correct’
posttest
Endwhile
➔ If the test is true, the commands will be carried out
➔ If the test is false the loop will stop.
Also note that if the test is false at the start of the process there
will be no iterations at all. That means in certain conditions, the
actions inside the loop will not be carried out even once.
ACTIVITY
What condition do you think would keep this
algorithm iterating?
What do you think would have to be indicated by
the user to stop this loop?
THE WHILE LOOP Consider this simple algorithm for adding up
a series of inputted numbers:
SYNTAX
Sometimes an algorithm needs to iterate
steps an unspecified number of times. In
set the total to 0
set more numbers to ‘yes’
programming, condition-controlled loops can
while more numbers is ‘yes’, repeat
be implemented using WHILE statements.
these steps:
This algorithm would keep iterating until the input a number
password is entered correctly. A condition- add the number to the total
controlled loop must be used because there ask ‘Any more numbers? Yes/No’
is no way of knowing in advance how many say what the total is
times a password will need to be entered
before it is correct. Activity
How do you think the above algorithm
works? State in your response the following:
●What is the control variable that will keep
track of value the user enters to either
terminate or continue to iterate?
●At what point is the condition tested to
determine when the loop will terminate or
continue to iterate?
●At what point in the loop is the control
THE WHILE LOOP
up a series ofSYNTAX
Consider this simple algorithm for adding The program works like this:
inputted numbers:
set the total to 0 Before the condition is tested, It must be set
set more numbers to ‘yes’ to an initial value “yes” at the beginning so
while more numbers is ‘yes’, repeat the code runs at least once
these steps:
input a number the ‘while’ statement is used to specify
add the number to the total where the iteration starts, that is, the
ask ‘Any more numbers? Yes/No’ condition which is tested would be ‘answer
say what the total is = “yes”, where ‘answer’ is used to control
the iteration (the control variable).
This algorithm would keep iterating until the The program tests the condition by checking
answer at the end of the loop is ‘No’, ie it if the variable ‘answer’ equals “yes”
will continue to iterate WHILE there are ●if the condition is true, the program
more numbers to add (yes). iterates
●if the condition is false, the program
A condition-controlled loop would be used moves on to the next step
because there is no way of knowing in
advance how many more numbers will need This program iterates as many times as is
to be entered before the algorithm stops. necessary and will keep iterating as long as
UNDERSTANDING
THE
The pre-testWHILE LOOP
and the post-test
statement in the loop is the same in
most situation as it is evaluating the
conditional expression. You can
identify them based on the Variable in
the conditional expression.
Once you enter the loop block, you
will not be able to go back to the pre-
test statement and in order to know
when to exit the loop the loop’s
conditional statement must be re-
evaluated, hence the use of the post-
test.
ACTIVITY
TYPES OF WHILE LOOP
While loops can either be counter controlled
or sentinel controlled.
Sentinel Controlled Loops
A sentinel is a special value or signal which
is normally entered by the user as a
condition of termination. Sentinel-controlled
repetition is sometimes called indefinite
repetition because it is not known in
advance how many times the loop will be
executed.
WORKING WITH SENTINEL
CONTROLLED WHILE LOOPS
Problem Statement
Write a pseudocode algorithm to calculate the
product of a series of numbers entered by the
user. Print the final product of all the numbers.
The algorithm will terminate when the user
enters 999 as a number.
Analysis
This algorithm will terminate once the user
enters 999. The pre-test/post-test statement
will be an input(signal) from the user
WORKING WITH SENTINEL
CONTROLLED WHILE LOOPS
Problem Statement
Write a pseudocode algorithm to calculate the
product of a series of numbers entered by the
user. Print the final product of all the numbers.
The algorithm will terminate when the user
enters 999 as a number.
Analysis
This algorithm will terminate once the user
enters 999. The pre-test/post-test statement
will be an input(signal) from the user
TYPES OF WHILE
LOOP
Counter Controlled Loops
The count is kept in a variable called an index
or counter. When the index reaches a certain
value the loop will end. Counter-controlled
repetition is often called definite repetition
because the number of repetitions is known
before the loop begins executing.
How is the counter-controlled
while loop different from the
WORKING WITH COUNTER
CONTROLLED WHILE LOOPS
Problem Statement
A variable has a starting value of 1. While the
variable is less than or equal to 5, add 1.5 to
the variable and display the results
Analysis
No input from the user is required, hence we
will initialize the counter to start at 1, as
indicated in the problem statement.
A pre-test/post-test is not explicitly used for
the counter controlled loop as the initialization
statement functions as the pre-test and the
increment/decrement of the counter functions
as the post-test.
The condition to iterate this loop is as long as
the counter is less than or equal to 5, hence
your conditional expression will be written
accordingly with the correct relational
WORKING WITH COUNTER
CONTROLLED WHILE LOOPS
Problem Statement
A variable has a starting value of 1. While the
variable is less than or equal to 5, add 1.5 to
the variable and display the results
Analysis
No input from the user is required, hence we
will initialize the counter to start at 1, as
indicated in the problem statement.
1
The value of the control variable in the pre-
test/post-test is not determined by the user.
For the counter controlled loop the
initialization of the control variable using an
assignment statement functions as the pre-
test and the increment/decrement of the
counter functions as the post-test.
The condition to iterate this loop is as long as
WHILE LOOPS CONCEPTS
REVIEWED
The while loop program works like this:
1.Initialize the control: The Control is
typically a variable that is associated
with a value that determines whether or
not the loop executes.
2.Testing the control against a condition
3.Executing the body of the loop
4.Update the value of the control inside
the loop block
5.Repeat STEP 2
The above steps can be used for both the
counter controlled or conditioned controlled
while loop.
The while logical test is generally flexible:
❏It can consist of more than one condition.
Eg. While (a>0) and (a<20) do
❏It can consist of more than one variable
based on problem statement eg. Is
terminated when 10 is entered as a number
WORKING WITH WHILE LOOPS - Practice Questions
Problem Statement Problem Statement
Construct a pseudocode algorithm to read a Write a pseudocode algorithm to find the
set of positive integers, terminated by 0, and highest and lowest number in a series of
print the remainder of their average as well as numbers entered by the user. The program
the largest integer entered. terminates when -1000 is entered as a
number. Output the highest and lowest
Problem Statement numbers entered.
Construct a pseudocode algorithm to do the
following: while the value of my_num is Problem Statement
greater than zero and less than or equal to 20, Design a pseudocode algorithm that reads
add 1 to it and display the results. a list consisting of the number of runs
scored by each batsman in the team.
Problem Statement Compute and print the average number of
Write a pseudocode to accept the scores of a runs scored by the team. The algorithm
series of students in a class. Calculate and terminates when -1 is entered as the
print the class average, also determine and number of runs.
print the highest grade. The program will
terminate when the user enters -99 as a score. Problem Statement
J is given an initial value of -5. Print the
value of J then add 1 to it. The program
Designing flowcharts for the
WORKING WITH WHILE LOOPS - FLOWCHARTS
Things to Note:
• A WHILE loop is a loop that repeats while some
condition is satisfied.
• The WHILE loop tests its condition at the beginning of
every loop.
• If the condition is false from the start, the sequence of
activities contained in the loop body never runs at all.
Pseudocode:
Initialization of variables
//initialise the loop variable
Pretest
WHILE condition Do
Loop Body
//update the loop variable
Posttest
ENDWHILE
Statements outside loop
After you initialize all variables (accumulators, counters and
comparison), the control flow enters the while loop at the
instruction: while (condition). This statement determines whether
the control enters the body of the loop. If the condition evaluates to
true, then the statements within the loop body are executed. Once
each statement in the loop block has finished executing, the control
flow jumps back to the first instruction, while (condition), and the
WORKING WITH SENTINEL CONTROLLED WHILE LOOPS -
Problem Statement FLOWCHARTS
1 Set total = 0
2 Display “Please enter a score, -1 to exit”
3 Input score //pretest
4 While score <> -1 do pre-test
5 Set total = total + score
6 Display “Please enter a score, -1 to exit”
7 Input score //post-test
8 Endwhile
9 Display total
Make your flowchart to match this problem.
1.Where on your flowchart would you put
the pre/post-test for the above
pseudocode?
post-
2.What statement is executed when the
test
loop terminates?
3.When the condition evaluates to false,
where on the flowchart would the last set
of statements be placed?
WORKING WITH COUNTER CONTROLLED WHILE LOOPS -
FLOWCHARTS
Problem Statement
J is given an initial value of -5. Print the value
of J then add 1 to it. The program terminates
when J is greater than 0.
A flowchart can also be used to represent the
flow of the iteration control structure. You
must have knowledge of the correct
shapes/symbols to be used based on the how
the lines of codes are to be executed.
The flowchart for the above problem
statement (to your right) contains a “loop”
that runs “while” a condition is true.
What condition must be true for the
loop body to be executed and what
symbol is used to represent this line
of code?
TRANSLATING PSEUDOCODE TO PASCAL - WHILE LOOPS
You will use the rules of the Pascal language such as := for
assignment, a semicolon after each statement, writeln or
readln for output and input respectively. The syntax for the
while loop in pascal follows the same sequence except you
are using a program language.
While conditions do
begin
:
(statements / commands) Translate this
: pseudocode to pascal,
ensuring you have a
end;
full program including
Problem Statement header, declaration
1 Set total = 0 and termination so
2 Display “Please enter a score, that
-1 to your
exit”program can
execute.
3 Input score
4 While score <> -1 do You will notice that there is a
5 Set total = total + score begin after the ‘do’ key word
6 Display “Please enter a score, -1 to exit” and instead of ‘endwhile’, it
7 Input score
8 Endwhile
is ‘end;’
9 Display total
TRANSLATING PSEUDOCODE TO PASCAL - WHILE LOOPS
Problem Statement
(a) Write a pseudocode algorithm to accept the
names and number of clubs registered for a series
of students at Ardenne High School. Count the
number of students who registered for 3 clubs.
Print the number of students who registered for 3
clubs. The program terminates when the user
enters “exit” for a student’s name.
(b) Translate the above pseudocode to PASCAL
Problem Statement
Using Pascal Repeat the following block of code
as long as the user indicates they want to:
❏Enter the names and ages of their family
members.
❏Count the number of family members who
are over the age of 40.
Print the final value.