Chapter 8

Data and Random Access


Page 361

8.1 In Program 8.1, dieroll.cc , to simulate twelve sided dice (sums from 2 to 24) requires 16 more variables, the same number of case alternatives in the switch statement and the same number of output statements.

When using an array/vector as in Program 8.2 only one constant, DICE_SIDES needs to be changed to simulate 12 sided dice.

8.2 To simulate three six-sided dice requires that the size of the array change from 2*DICE_SIDES + 1 to 3*DICE_SIDES + 1 and that the statement

    int sum = d.Roll() + d.Roll();

be replaced by

    int sum = d.Roll() + d.Roll() + d.Roll();

8.3

    const int SIZE = 512;
    Vector<double> doubVec(SIZE);
    Vector<int> intVec(SIZE/2);

    int k;
    for(k=0; k < SIZE; k++)
    {
        doubVec[k] = 2.0*k;
        if (k % 2 == 0) intVec[k/2] = 2*k;
    }

8.4 It IS possible to have a vector of Balloon , since there are NO parameters for a Balloon constructor. Also ok for Coin vector, since constructor has no parameters.

8.5


Vector<string> compscientists(5);
compscientists[0] = "Grace";
compscientists[1] = "Alan";
compscientists[2] = "John";
compscientists[3] = "Ada";
compscientists[4] = "Blaise";

// using built-in array
// string compscientists[] = {"Grace","Alan","John","Ada","Blaise"};

int k;
for(k=0; k < 5; k++)
{
    Sing(compscientists[k]);
}

8.6 Create a definition as shown below at the beginning of the program and then use it.

    const int MAX = 10;
    int list[MAX];
    // alternative, vector definition: Vector<int> list(MAX);

8.7 It is NOT possible to have the size of a built-in array be determiend at run-time using standard C++ (until we learn about pointers). Some compilers do let you do this, but it is NOT standard.

8.8 Be creative, imagine a reason.

8.9

while (num != 0 && count < MAX)
where MAX is a global constant (see problem 6 above).