www.gibmonks.com

Main Page




Previous Page
Next Page

[Page 389 (continued)]

Answers to Self-Review Exercises

7.1

a) arrays, vectors. b) name, type. c) subscript (or index). d) constant variable. e) sorting. f) searching. g) two-dimensional.

7.2
  1. False. An array can store only values of the same type.

  2. False. An array subscript should be an integer or an integer expression.

  3. False. The remaining elements are initialized to zero.

  4. True.

  5. False. Individual elements of an array are passed by value. If the entire array is passed to a function, then any modifications will be reflected in the original.

7.3
  1. const int arraySize = 10;

  2. double fractions[ arraySize ] = { 0.0 };

  3. fractions[ 3 ]

  4. fractions[ 4 ]

  5. fractions[ 9 ] = 1.667;

  6. fractions[ 6 ] = 3.333;

  7. cout << fixed << setprecision ( 2 );
    cout << fractions[ 6 ] < < ' ' fractions[ 9 ] << endl;
    

    Output: 3.33 1.67.

  8. for ( int i = 0; < arraySize; i++ )
      cout << "fractions[" < i << "] = " << fractions[ i ] << endl;
    

    [Page 390]

    Output:

    fractions[ 0 ] = 0.0
    fractions[ 1 ] = 0.0
    fractions[ 2 ] = 0.0
    fractions[ 3 ] = 0.0
    fractions[ 4 ] = 0.0
    fractions[ 5 ] = 0.0
    fractions[ 6 ] = 3.333
    fractions[ 7 ] = 0.0
    fractions[ 8 ] = 0.0
    fractions[ 9 ] = 1.667
    
7.4
  1. int table[ arraySize ][ arraySize ];

  2. Nine.

  3. for ( i = 0; i < arraySize; i++ )
    
        for ( j = 0; j < arraySize; j++ )
           table[ i ][ j ] = i + j;
    

  4. cout << "     [0] [1] [2]" << endl;
    
    for ( int i = 0; i < arraySize; i++ ) {
        cout << '[' << i << "] ";
    
        for ( int j = 0; j < arraySize; j++ )
           cout << setw( 3 ) << table[ i ][ j ] << " ";
    
        cout << endl;
    

    Output:

           [0]  [1]  [2]
    [0]     1    8    0
    [1]     2    4    6
    [2]     5    0    0
    
7.5
  1. Error: Semicolon at end of #include preprocessor directive.

    Correction: Eliminate semicolon.

  2. Error: Assigning a value to a constant variable using an assignment statement.

    Correction: Initialize the constant variable in a const int arraySize declaration.

  3. Error: Referencing an array element outside the bounds of the array (b[10]).

    Correction: Change the final value of the control variable to 9.

  4. Error: Array subscripting done incorrectly.

    Correction: Change the statement to a[ 1 ][ 1 ] = 5;


Previous Page
Next Page