ALL Chapter 4 Bookwork Rewritten with Answers

Bookwork 4.2 #1-9

  1. Indicate which of the following are valid function declarations. Explain what is wrong with those that are invalid.
    1. round_tenth (double x);

      Answer: invalid, missing type return.

    2. double make_changes (X, Y);

      Answer: invalid missing types on formal parameters.

    3. int max (int x, int y, int z);

      Answer: valid.

    4. char sign (double x);

      Answer: valid.

    5. void output_string(apstring s);

      Answer: valid.

  2. Find all the error in each of the following functions:
    1. Code Snippet:
      int average (int n1, int n2);
      {
      return N1 + N2 / 2;
      }

      Answer: The parameters are declared using lower case ‘n’, but the identifiers in the function block use uppercase ‘N’.

    2. Code Snippet:
      int total (int n1, int n2);
      {
      int sum;
      return 0;
      sum = n1+n2;
      }

      Answer: The return statement should be positioned so that it is after all computations have been completed.

  3. Write a function for each of the following:
    1. Round a real number to the nearest tenth.

      Answer: Code Snippet:
      double round_tenths (double num)
      {
           double temp;     temp = num * 10;      //multiplies original number by 10 therefore moving the decimal 1 place.
           temp = temp +0.5;    //adjust for rounding
           temp = floor(temp);  //truncates the value at the decimal point
           return (temp/10);      //moves decimal back 1 place.
      }

    2. Round a real number to the nearest hundredth.

      Answer: Code Snippet:
      double round_hundredths (double num)
      {
           double temp;     temp = num * 100;      //multiplies original number by 100 therefore moving the decimal 2 places.
           temp = temp +0.5;      //adjust for rounding since we are using floor.
           temp = floor(temp);    //truncates the value at the decimal point (floor always rounds down).
           return (temp/100);      //moves decimal back 2 place.
      }

    3. Convert degrees Fahrenheit to degrees Celsius.

      Answer: Code Snippet:
      double change_scale (double fahrenheit)
      {
           return (5/9 * fahrenheit – 32);      //subtracts 32 then multiplies by 5/9
      }

    4. Compute the charge for cars at a parking lot; the rate is 75 cents per hour or any fraction thereof.

      Answer: Code Snippet:
      double parking_charge (double hours)
      {
           int charged_hours;
           const double RATE = 0.75;
           charged_hours = ceil(hours);     //ceil always rounds up
           return (charged_hours * RATE);      //rate * time = total
      }

  4. Write a program that uses the function you wrote for calculating parking lot charges to print a ticket for a customer who parks in the parking lot. Assume the input is in minutes.

    // Example program
    #include <iostream>
    #include <string>
    #include <cmath>
    using namespace std;

    double parking_charge (double hours)
    {
    int charged_hours;
    const double RATE = 0.75; charged_hours = ceil(hours); //ceil always rounds up
    return (charged_hours * RATE); //rate * time = total
    }
    int main()
    {
    double minutes;
    cout << “How many minutes have you been parked here? n”;
    cin >> minutes;
    double hours = minutes/60.0;
    cout << parking_charge(hours);
    }

  5. Write two functions (square and cube) to write a program which prints the square and cube of any user given integer.

    // Example program
    #include <iostream>
    #include <string>
    #include <cmath>
    using namespace std;

    double square(int integer)
    {
    return integer*integer;
    }

    double cube(int integer)
    {
    return integer*integer*integer;
    }

    int main()
    {
    int userinteger;
    cout << “Give me a number and I will square it and cube it for you. n”;
    cin >> userinteger;

    cout << “The square of ” << userinteger << ” is “<< square(userinteger)<< “. and the cube of ” << userinteger << ” is ” << cube(userinteger)<< “.”;
    }

  6. Write a program that contains a function that allows the user to enter a base (a) and an exponent (x) and then have the program print the value of a to the x power.

    Answer: This is a trick question. pow() does this.
    // Example program
    #include <iostream>
    #include <string>
    #include <cmath>
    using namespace std;

    double power(double base, double exponent)
    {
    return pow(base, exponent);
    }

    int main()
    {
    int userbase;
    int userexponent;
    cout << “Give me a base: n”;
    cin >> userbase;
    cout << “Give me an exponent: n”;
    cin >> userexponent;
    cout << userbase << ” to the “<< userexponent << ” is ” << power(userbase,userexponent) << “.”;
    }

  7. What role do parameters play in a function?

    Answer: Parameters send values to functions via call statements.

  8. Explain the difference between formal parameters and actual parameters.

    Answer: Formal parameters are listed in the parentheses of the function header. They must include the data type as well as the identifier name.
    Actual parameters are listed in the parentheses of the call to the function. Only identifier names are listed.

  9. Why is it a good idea to write functions that are as general as possible?

    Answer: So they are reusable as many times as possible

Bookwork 4.3 #1-3

  1. What is the difference between reference and value parameters?

    Answer: Value parameter is not to be changed and returned by the function, where the reference parameter is to be changed and sent back to the caller as new values.

  2. Write  and test a function int_divide that receives two integer values and two integer variables from the caller. When the function completes the execution, the values in these variables should be the quotient and the remainder produced by dividing the second value by the first value. Be sure to name your parameters descriptively so as to aid the reader of the function.

    Answer: Code Snippet:
    void int_divide (int divisor, int dividend, int &quotient, int &remainder)
    {
         quotient = dividend / divisor;
    remainder = dividend % divisor;

    }

  3. When would you use a constant reference parameter?

    Answer: Constant reference parameters are used when the original data should not be altered by the function but the size of the data is relatively large.

Bookwork 4.4 #1-3

All three questions combined into one programming challenge.

Write a full program that has the following components.

  • Basic program structure including an int main() which calls each of the following functions.
  • A function called get_data which
    • Prompts the user for an input integer and reads it.
    • Receives nothing.
    • Returns input integer (assumes non-negative).
  • A function called compute_result which:
    • Computes the square root of its argument.
    • Receives integer value that was input.
    • Returns square root of the input integer.
  • A function called print_result which:
    • Displays both the input integer and its square root.
    • Receives integer input value and float square root.
    • Returns nothing.

Answer: Code Snippet:

// Example program
#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int get_data()
{
int userinteger;

cout << “Give me a positive integer and I will square root it for you.” << “n”;
cin >> userinteger;
return userinteger;
}

double compute_result(int integer)
{
return sqrt(integer);
}

void print_result(int integer, float root)
{
cout << “The square root of ” << integer << ” is approximately ” << root << “.”;
}
int main()
{
int userinteger = get_data();

float root = compute_result(userinteger);

print_result(userinteger, root);
}

Bookwork 4.5 #1-12

  1. Explain the difference between local and global identifiers.

    Answer: Local identifiers are valid only in the main block or sunblock where they are declared. Global identifiers are valid in the main program block and all sunblocks. These are declared before the main block.

  2. State the advantages of using local identifiers.

    Answer: The advantages of using local identifiers are:
    1. They help to avoid side effects by eliminating the possibility of accidentally changing values in global variables.
    2. They facilitate debugging.
    3. They enhance the portability of functions.
    4. They facilitate top-down design.

  3. Discuss some appropriate uses for global identifiers. List several constants that would be appropriate global definitions.

    Answer: Some appropriate uses of global identifiers are:
    1. function names
    2. type names
    3. constants

  4. What is meant by the scope of an identifier?

    Answer: The scope of an identifier refers to the area(s) of the program where it may be used.

  5. SKIP
  6. Review the following program:
    Code Snippet:
    int main()
    {
    int a, b;
    double x;
    char ch;

    }
    int sub1 (int a1)
    {
    int b1;

    }
    int sub2(int a1, int b1)
    {
    double x1;
    char ch1;

    }

    1. List all global variables.

      Answer: No Global Variables

    2. List all local variables.

      Answer: a, b, x, ch, b1, x1, ch1

    3. Indicate the scope of each identifier.

      Answer:
      Main program block: a, b, x, ch
      sub1 function block: a1, b1
      sub2 function block: a1, b1, x1, ch1

  7. SKIP
  8. SKIP
  9. SKIP
  10. SKIP
  11. SKIP
  12. Discuss the advantages and disadvantages of using the same names for identifiers in a subprogram and the main program.

    Answer: Using the same names for identifiers both in the main program and in the function sunblocks allows the programmer to code quickly without having to think up and keep track of various variable names. However, a decision to reuse names may very likely lead to unwanted and unexpected side effects when variables change value when they are not supposed to. Also, duplicate names may not have the same meaning or purpose in different contexts.

Bookwork 4.6 #1-4

  1. Why is it a good idea to put commonly used functions in a program library?

    Answer: It is a good idea to put commonly used functions into a program library to allow easy access to a previously created function which can be applied in a new program. Library functions can be included in any program as it is needed.

  2. Discuss the difference between a library header file and a library implementation file. What are the roles and responsibilities of each file?

    Answer: The library header file serves as the communication link between the implementation of its library and its users. Comments documenting the function go with the declarations in the header file.
    The implementation file includes the library header file before defining the functions. This order is important because the compiler checks to make sure the function declarations in the header file match the headings in the implementations file.

  3. Discuss how C++ preprocesses code in library files before compilation. Be sure to address the role of the directives #include, #ifndef, #define, and #endif in this process.

    Answer: The functions are declared and this code is saved in a library header file. The name of this file should have a .h extension so that it may be included in other programs. The implementation file contains the code that calls the library functions, and it should be saved with a cpp extension.
    The directives #ifndef, #define, and #endif are used to prevent the compiler from including a library file more than one time in an application at compile time.
    The first directive, #ifndef, asks if a file identifier has been defined. If it has, the library file has already been preprocessed and the compiler skips to the #endif at the end of the file. If the file identifier has not been defined, the preprocessor will get to the #define directive after preprocessing the library file. This directive then makes visible a global file identifier, so that subsequent inclusions after this one will behave as described in the paragraph above.
    The #endif is used to signal the end of the library function.
    In order to include user-defined library functions, the #include statement will use quotes around the header file name instead of the symbols used for the built-in library functions.

  4. Create a program library named mymath. This library should define functions for computing the areas of computing the areas of rectangles, circles, and triangles.

Bookwork 4.7 #1-6

  1. Design, implement, and test a function for drawing parallelograms. Like a triangle, a parallelogram can be specified with three points.

    Answer: Code Snippet:
    void parallelogram (int x1, int y1, int x2, int y2, int x3, int, y3)
    {
    move(x1, y1);
    lineto(x2, y2);
    lineto(x3, y3);
    lineto(x3-x2+x1,y3-y2+y1);
    lineto(x1, y1);
    }

  2. SKIP
  3. Design, implement, and test a function for drawing rectangles that uses relative coordinates. The function should expect parameters that specify the coordinates of one corner and the rectangles height and width.

    Answer: Code Snippet:
    void rectangle (int x, int y, int length, int width)
    {
    move(x, y);
    linerel(0, height);
    linerel(width, 0);
    linerel(0, -height);
    linerel(-width, 0);
    }

  4. Design, implement, and test the fill_circle function as mentioned in Example 4.8.

    Answer: Code Snippet:
    void fill_circle (int x, int y, int radius, int fill_pattern, int fill_color, int border_color)
    {
    int color = getcolor();     setcolor(border_color);
    circle(x, y, radius);
    setfillstyle(fill_pattern, fill_color);
    floodfill(0, radius/2, border_color);
    setcolor(color);
    }

  5. Rewrite the face function of Example 4.7 so that it draws the eyes as filled circles.

    Answer: Code Snippet:
    void face (int center_x, int center_y, int size)
    {
    int color = getcolor();     circle(center_x, center_y, size);
    fill_circle(center_x-size/4, center_y-size/4, 2, HATCH_FILL, BLUE, WHITE);
    fill_circle(center_x+size/4, center_y+size/4, 2, HATCH_FILL, BLUE, WHITE);    lineto(x3-x2+x1,y3-y2+y1);

    setcolor(color);
    }

  6. State two reasons why the development of programmer defined graphics functions is beneficial.

    Answer: The development of programmer-defined graphics functions is a good thing because:
    1. it will extend the toolbox of graphics functions that are built into the compiler.
    2. redundant code will be reduced to a function that will be called multiple times.
    3. the task of drawing complex shapes can be simplified by creating functions for its component shapes.

Bookwork Chapter 4 Review #1-27

  1. Explain the difference between a value parameter and a reference parameter. Give an example of how each is used.

    Answer:
    A value parameter is used to pass to a function a copy of the value of a variable in the sunblock where the call statement is located. The receiving function then uses the copy of the value to perform whatever operations are defined for that function. For example, values are passed to a function where they are output in a complete sentence.

    A reference parameter may be used to send back new values from the function to the sunblock where the call statement is located or to received a value from the call statement in the sunblock, alter it, and substitute the adjusted value in place of the original. For example, a radius value is to be input in a get_data function and that value is to be used in another function that calculates the area of the circle having that radius value.

  2. Explain the difference between an actual parameter and a formal parameter.

    Answer: Actual parameters are listed in the calling statement and consist only of the identifier names. Formal parameters are in the function heading and consist of both a data type and a name for each identifier.

  3. A function is declared as
    void sample_func(int a, double &b, char c);
    Which parameters in this declaration are reference parameters and which are value parameters?

    Answer: The reference parameter is b. The value parameters are a and c.

  4. Valid or invalid function call?
    sample_func(int1, double1, ch1);

    Answer: valid

  5. Valid or invalid function call?
    sample_func;

    Answer: invalid – missing parentheses and parameter names

  6. Valid or invalid function call?
    sample_func();

    Answer: invalid – missing parameter names

  7. Valid or invalid function call?
    sample_func(int int1, double double1, char ch1);

    Answer: invalid – should not contain data types.

  8. Valid or invalid function call?
    sample_func(int1, double1);

    Answer: invalid – function heading is expecting 3 parameters

  9. Valid or invalid function call?
    sample_func(int, double, char);

    Answer: invalid – lists types rather than identifiers.

  10. Valid or invalid function call?
    sample_func(10, double1, ‘A’);

    Answer: valid

  11. Valid or invalid function call?
    sample_func(10.5, double1, 66);

    Answer: valid

  12. Valid or invalid function call?
    sample_func(10, 10.5, ‘A’);

    Answer: invalid – second parameter needs to be a variable because it is a reference parameter.

  13. SKIP
  14. SKIP
  15. SKIP
  16. SKIP
  17. SKIP
  18. SKIP
  19. SKIP
  20. SKIP
  21. SKIP
  22. SKIP
  23. SKIP
  24. SKIP
  25. SKIP
  26. SKIP
  27. Why are reference parameters used in a function designed to initialize variables?

    Answer: Functions designed to only initialize variables, either by input or assignment, need to have those values passed on to other functions so that they can be used in any calculations and output that the program was written to do.

Leave a Reply