Professional Documents
Culture Documents
The While Loop: Objectives
The While Loop: Objectives
The While Loop: Objectives
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
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;
}
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.
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
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
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;