Following are the first eight elements from six numerical sequences:
Fibonacci: 1, 1, 2, 3, 5, 8, 13, 21
Lucas: 1, 3, 4, 7, 11, 18, 29, 47
Pell: 1, 2, 5, 12, 29, 70, 169, 408
Triangular: 1, 3, 6, 10, 15, 21, 28, 36
Square: 1, 4, 9, 16, 25, 36, 49, 64
Pentagonal: 1, 5, 12, 22, 35, 51, 70, 92
Our program must display a pair of elements from a sequence and allow the user to guess the next element.
If the user guesses right and wishes to continue, the program then displays a second pair of elements, then
a third, and so on. How might we do that?
If succeeding element pairs are taken from the same sequence, the user, recogni zing one pair, recognizes
them all. That is not very interesting. So we'll pick an element pair from a different numeric sequence with
each iteration of the main program loop.
For now, we'll display a maximum of six element pairs per session: one pair from each of the six
sequences. We'd like to implement this so that we can loop through the display of the element pairs
without having to know which sequence we are disp laying with each loop iteration. Each iteration must
have access to three values: the element pair and the element that follows them in the sequence.
The solution we discuss in this section uses a container type that can hold a contiguous sequence of integer
values that we can reference not by name but by position within the container. We store 18 values in the
container as a collection of six tuples: The first two represent the element pair to display; the third
represents the next sequence element. With each iterati on of the loop, we add 3 to the index value, in this
way stepping through the six tuples in turn.
In C++, we can define a container as either a built-in array or an object of the stan-dard library vector class.
In general, I recommend the use of the vector class over that of the built-in array. However, a great deal of
existing code uses the built-in array, and it is important to understand how to use both representations.
To define a built-in array, we must specify the type of element the array is to hold, give the array a name,
and specify a dimension — that is, the number of elements the array can hold. The dimension must be a
constant expression — that is, an expression that does not require run-time evaluation. For example, the
following code declares pell_seq to be an array of 18 integer elements.
To define a vector class object, we must first include the vector header file. The vector class is a
template, so we indicate the type of its element in brackets following the name of the class. The dimension is placed in parentheses; it does not need to be a constant expression. The following code defines
pell_seq as a vector class object holding 18 elements of type int . By default, each element is initialized
to 0.
Running Codes
No comments:
Post a Comment