Next: The do-while statement
Up: The while statement
Previous: Review Questions
A set of numbers is to be entered to the computer and the number of negative and the number of positive values entered are to be output. All the numbers lie between -100.0 and 100.0.Now implement your algorithm as a C++ program using a
while
loop
and a sentinel value to terminate input. Make up a suitable small set of
data and choose a suitable sentinel value to terminate input and test your
program.
int
variable possible to be generated then errors
will occur! The form the error will take will depend on the compiler
being used, it might generate erroneous results and/or get stuck in an
infinite loop.
The onset of this problem can be delayed by
declaring the integer variables holding the limit and the power of two as
being of type long int
which will allow these variables to take
values up to a 10 digit integer. It is important while programming to
remember that there are limitations on the size and precision that
numerical values can take, if these limitations are not kept in mind
nonsensical results can be produced.
#include <stdlib.h> #include <time.h> #include <iostream.h> void main() { int r; // random integer; int i = 0; // control variable srand(time(0)); // initialise random number generator while (i < 10) { r = rand(); // gets random int in 0-RAND_MAX cout << "Random integer was " << r; i++; } }Note that the function
srand
is used once at the
beginning of main
, this ensures that the random number sequence will
start at a different value each time that the program is run. If the
call of srand
was left out then the program would deliver
exactly the same results each time it was run, not very random! The
function rand()
returns a random integer in the range 0 to
RAND_MAX
. RAND_MAX
is a const int
defined in the
include file stdlib.h
. The use of time(0)
as an argument to
srand
ensures that a new starting value is used each time the
program is run. Note that the inclusion of the files stdlib.h
and
time.h
is required before these functions can be used.
Now extend the above program so that it generates n
random
numbers, where n
is entered by the user, and counts how many of
the random integers generated are less than a half of RAND_MAX
. If
the random number generator is producing a uniform spread of random
numbers in the interval then this should converge towards a half of
n
. Execute your program with increasing values of n
(but not bigger than 32767).