The While Loop: Objectives

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Objectives

 To recognise when a WHILE loop is


needed.
The While Loop  To be able to predict what a given WHILE
loop will do.
1E3  To be able to write a correct WHILE loop.
Topic 6  To be able to use a WHILE for handling
input terminated with a sentinel.

6 While Loops 1 6 While Loops 2

Textbook WHILE Loops


 This topic is covered in the first part of  WHILE some condition holds DO some
Chapter 5. action repeatedly
 WHILE there is more dessert
eat a spoonful;
 You should now read up to the end of the
 WHILE investment has not doubled
Fibonacci number programming example.
leave it for another year;
 WHILE notes not understood
study them some more;

6 While Loops 3 6 While Loops 4

1
WHILE loops in C++ Example
 while ( condition )
action;
 while ( condition )
{
multiple statements
}
 Note there is no ; after the condition’s ) or
after the closing } Note: We will see later that this behaviour would be more
suited to a FOR loop.
6 While Loops 5 6 While Loops 6

Flowchart for while Do zero or more times


while (<Condition>)
In <Statement>
 Note that a while loop causes the body to
be executed zero or more times.
 From the flowchart you can see that if the
T
<Condition> <Statement> condition is initially true control goes straight
through, without executing statement.
If the <Condition> evaluates to true, the flow of  Later we’ll look at a related construct that
program execution exits via the T (for True) branch,
F
Out flowing to the <Statement>. When the carries out the loop body one or more
<Statement> completes, execution flow loops
around to perform the whole while construct again. times.
If the condition evaluates to false, execution flows to
the Out terminal, on to the statement following the
while construct.
6 While Loops 7 6 While Loops 8

2
Infinite Loops Be careful …
 Make sure your loop body changes the  What’s will this loop do?
loop condition.  x = 1;
 This loop will never end: while (x != 12)
{
cout << x << “\n”;
x = x + 2;
}

6 While Loops 9 6 While Loops 10

Correct WHILE loops Double an investment


 Initialise the condition variables  How many years will it take to double 1000 euro
if the annual interest is 5%?
 countdown = 5
 The basic loop is
 Test the condition  while value < (2 * initial-value)
 countdown > 0 add another year’s interest to value
 Modify the condition variables  But this doesn’t give us a value for the number
of years it takes.
 countdown = countdown - 1
 See doubleinvestment.cpp
 This should generally move the condition
 Exercise: Turn this into a program that reads in
closer to being false. the initial investment and interest rate.

6 While Loops 11 6 While Loops 12

3
Quick self-test Counter controlled while loops
 Show the output of this code if x is of type int  A while loop can be used to
 x = 10;  read 20 numbers, and average them
while ( x > 0)
{  printout the value of an investment for each
cout << x << “\n”; of 35 years
x = x – 3;  These are counter controlled loops.
}
 But we will prefer FOR loops for loops
 Show the output if the condition is changed that are to be executed a specific number
from (x > 0) to (x < 0). of times.

6 While Loops 13 6 While Loops 14

Counter-controlled Sentinel controlled loops


 We’ll use these a lot so pay attention!
 While loops are perfect for handling sequences
of input of unknown length.
 If a special “sentinel” value terminates the
sequence, then we use a sentinel controlled loop.
 E.g. use 0 to terminate series of student numbers
 Use a negative number to terminate a sequence of
exam results

6 While Loops 15 6 While Loops 16

4
Sentinel controlled loop Sentinel controlled Exercise
 Add a sequence of numbers terminated by
a 0.
 See add-sequence.cpp
 Alter it to get average, min and max.
Deal with the variable
 Test whether a sequence of numbers is all
even.
 This involves a boolean flag to keep track of
whether a non-even has been found.
 See testsequence.cpp

6 While Loops 17 6 While Loops 18

Flag controlled loops Number-guessing game


 Example 5.6 in textbook
 Program generates a random number
between 1 and 100, and then asks the user
to guess the number. Responds
 “Guess a lower number” or
 “Guess a higher number”

 till user enters the correct number.

6 While Loops 19 6 While Loops 20

5
Random numbers Another WHILE exercise
 A random integer between 1 and 100 is  Convert your feet to centimetres program
generated using
into one which asks the user if he’d like to
 (rand() + time(0)) % 100
 rand() may produce the same number each
do another conversion.
time! char answer = ‘y’; initialise
 So add an integer based on the current time: while (answer == ‘y’) … test
 time(0) { get and convert another
 Convert to 1..100 range by getting the remainder length … …
of dividing the random integer by 100 i.e. % 100 . . .
 rand() is in cstdlib library; time() is in ctime cout << “Again?(y/n):”;
cin >> answer; update
}
6 While Loops 21 6 While Loops 22

Program Style - Constants Program Style - Constants


 Better to use a constant

 37 is used repeatedly here, but it’s significance is


not clear
 It would be easy to make a mistake entering it.  Constants can’t be updated by the program.
 To change a constant (e.g. to 98.7) just have to
change one place.
6 While Loops 23 6 While Loops 24

6
Constants Next …
 Another example:  The next construct we’ll see is the FOR
const double PI = 3.1415
loop.
 The name of the constant should be more
meaningful than the number.  FOR is another way of doing something
 It is common practice to name constants with all repeatedly
capitals (NORMAL_TEMP, PI)  But usually for a predictable number of times
 Practical 3 and more realistic variants would be  Counter controlled loops.
a good place to use lots of constants:
 double TAXRATE = 0.2; PRSI = 0.25;
 tax = gross_wage * TAXRATE;

6 While Loops 25 6 While Loops 26

You might also like