PIC 10A sec. 3, Spring 2001, UCLA

 

Instructor: Ivo Dinov, Asst.Prof.

Mathematics, Neurology, Statistics

http://www.math.ucla.edu/~dinov/10a.3.01s/

 

Final Exam Study Guide

 

Exam: Sun., June 10, 2001, 3:00 – 6:00 PM, UCLA Young CS76

 

 

I. Part One:

1. Given the structure and structure variable declaration:

struct CDAccount

{

    double balance;

    double interest_rate;

    int term;

    char initial1;

    char initial2;

};

CDAccount account;

What is the type of each of the following? Mark any that are not correct.

a) account.balance

b) account.interest_rate

c) CDAccount.term

d) savings_account.initial1

e) account.initial2

f) account

2. A ____________ __________ value can be viewed as a collection of values.

 

 3. A structure value can be viewed as a ____________ of values.

 

 4. What is the error in the following structure definition? Give, in your words, the error message your compiler would give for this error.

struct A

{

    int b;

    int c;

}

int main()

{

    A x;

    // other code

}

 

5. Given the following struct definition.

struct A

{

    int member_b;

    int member_c;

};

 

Declare X to have this structure type. Initialize the members of X, member_a and member_b, to the values 1 and 2, respectively.

Note: This requests an initialization, not an assignment of the members. This distinction is important and will be made in the text in a later chapter.

 

6. NOTE: The text does not mention what happens when there are too few or too many initializers. This problem addresses that question. The student should have investigated this issue in studying the language.

Here is an initialization of a structure type.Tell what happens with each initialization. Note any problems with these initializations.

struct Date

{

    int month;

    int day;

    int year;

};

Date due_date = {12, 21};

Date due_date = {12, 21, 1995};

Date due_date = {12, 21, 19, 95};

Date due_date = {12, 21, 95};

 

7. Consider the following struct type definitions:

struct Date

{

    int month;

    int day;

    int year;

};

struct PersonInfo

{

    double height; // inches

    int weight; // pounds

    Date birthday; // struct above

};

PersonInfo person1 = {67.5, 195, {3, 21, 1950} };

Assume the following code fragments are embedded in a correct program with the above structure variable definition and initialization. What output will be produced form the following code fragments?

a) Date birthday, due_date;

b) cout << person1.height << endl;

c) cout << person1.birthday.day << endl;

d) cout << person1.weight << endl;

e) // person1 goes on a diet!

f) person1.weight = 166;

g) cout << person1.weight << endl;

 

8. Consider the following type definition. What output is produced if this code is embedded in a correct program?

struct JacketType

{

    char style;

    int chest_size;

    char length; // s)hort, r)egular, l)ong

    double price;

};

JacketType jacket1, jacket2;

jacket1.style = S;

jacket1.chest_size = 46;

jacket1.length = 's';

jacket1.price = 125.95;

cout << "jacket1: " << endl << jacket1.style << endl

     << jacket1.chest_size << endl << jacket1.length

     << endl << "$" << jacket1.price << endl;

 

9. Write a definition of a structure type for records consisting of a person's wage rate, accrued vacation (which is some whole number of days), and status (which is either hourly or salaried). Represent the status as one of the two char values 'H' and 'S'. Call the type EmployeeRecord.

 

10. Consider the following structure definition and declaration of a structure variable:

struct Grades

{

    int student_number;

    int quiz1;

    int quiz2;

    int midterm;

    int exam;

    char grade;

};

Grades gradebook;

Write the C++ references to the following items in gradebook:

a) the student number

b) the midterm grade

c) the exam grade

d) the grade on the second quiz

e) the course grade

11. Given the structure definition, structure variable declaration, and function declaration (prototype), write a function definition for the function that satisfies the precondition and postcondition.

struct Grades

{

    int student_number;

    int quiz_average;

    int midterm;

    int exam;

    char grade;

};

Grades gradebook;

void fix_exam_grade( Grades& gradebook_entry );

//Precondition: The function fix_exam_grade is correctly called

//with a value assigned to the exam member

//Postcondition:

//the exam member is increased by 10 points.

 

12. Given the structure definition, structure variable declaration, and function declaration (prototype), write a function definition for the function that satisfies the precondition and postcondition.

struct Grades

{

    int student_number;

    int quiz_average;

    int midterm;

    int exam;

    char grade;

};

Grades gradebook;

void read_grades( Grades& gradebook_entry );

//Precondition: Function read_grades is correctly called

//Postcondition: Gradebook is filled with values read from keyboard.

//Except for grade. It is to be computed later by another function.

 

13. Describe the distinction the text makes between a struct and a class.

 

14. Which of the following are legal access to the class or struct members?

struct S            class C            class D

{                   {                  {

    int x;              int x;         public:

    int y;              int y;             int x;

}                   private:               int y;

S s;                    int z;         private:

                    };                     int z;

                    C c;               };

                                       D d;

a) s.x

b) c.x

c) d.x

d) c.z

e) d.z

 

15. Explain what public and private do in a class definition.

 

16. Mention at one place where you must use the 'scope resolution operator' ::.

17. Within this function definition, month and day are members of the class DayOfYear.  Explain why we do not precede month or day with some object name and a 'dot' operator.

void DayOfYear::output()

{

    cout << "month = " << month

         << ", day = " << day << endl;

}

 

18. True or False. The scope resolution operator :: is used to associate a function or data member with a particular class, whereas the dot operator is used to associate a function or data member with a particular object.

If true, give an example of each usage, if false, explain the correct usage.

 

19. Given the class definition, provide a member definition for the member function set:

class Temperature

{

public:

    void set(double new_degrees, char F_or_C );

    // sets member variables to the values in the arguments

private:

    double degrees;

    char scale; //(F)ahrenheit, (C)elcius

};

20. True or False. The functions or data members declared in the private: section of a class can be accessed only in the definition of those functions declared in the public: portion of that class.

 

21. True or False. The functions or data members declared in the private: section of a class can be accessed only in the definition those functions declared in the public: portion of that class.

 

22. True or False. The functions or data members declared in the private: section of a class can be accessed only in the definition those functions declared in that class

 

23. Describe in terms of who needs access to class members why the public members should come first in a class definition.

 

24. Explain why data members, in particular should be placed in the private section of a class.

 

25. Suppose your program contains the following class definition.

class A

{

public:

    // set a and b to 0

    A(double new_a, double new_b); // create an A object, setting

    // a and b to arguments

    double get_a(); // fetch value for a

    void increment_a();

private:

    double a;

    double b;

    void increment_b();

    double get_b(); // fetch value for b

};

A u, v(3.4, 5.6);

Which of these statements are legal in your main function?

a) u.b = 50.5;

b) v.increment_a();

c) v.increment_b();

d)

if (u == v)

    cout << "The world is coming to an end!" << endl;

else

    cout << "Maybe he was a bad Prophet, after all." << endl;0

// These are declarations for rest of questions.

double a, b = 49.5;

e) a = get_a();

f) b = get_b();

g) u = v;

 

26. Given the class definition below, assume that the member functions have been defined.Assume further that the uses are embedded in the main function of a correct program.Which purported uses of the class members is legal? Explain in either case.

class A

{

public:

    A(int x);

    int access_x();

private:

    int x;

};

a) A a;

b) A a(1);

c) int z = access_x();

d) int z = a.x;

e) int z = a.access_x();

 

27. Given the following class definition, what do these lines of code appear to be doing? What does the following actually do?

class A

{

public:

    //other members ...

    A();

    A(int);

private:

    int x;

};

// definitions of the member functions

a) A x();

b) A y(1);

c) A z = A(1);

d) A w;

 

28. This class has two constructors named the same. How does C++ tell which constructor to call in the following situations?

class A

{

public:

//other members ...

    A();

    A(int);

private:

    int x;

};

// definitions of the member functions

a) A x();

b) A y(1);

c) A z = A(1);

d) A w;

 

29. What is a data type? Hint: A data type has two parts.

 

30. What are the requirements for a user defined type to be eligible to be called an ADT (Abstract Data Type)?

 

31. True or False. The set of integers ranging from -MAXINT to MAXINT make up the int data type.

 

32. When you use C++ classes to define an ADT, do you make the data members public or private? Should the member functions be public or private? Explain.

 

33. When you use C++ classes to define an ADT, do you make helping functions public or private? Why?

 

34. When you define an ADT with a C++ class, what items in the class are part of the interface and which are implementation?

 

35. You have been involved writing a program that uses an ADT implemented as a C++ class purchased in source from another company. You are assigned the task of writing the main function for a program as well as any nonmember functions used in the main function of this program. What parts of the code body of the ADT must you read and what parts can you safely ignore?

 

 

 

II. Part Two:

 

1.     Name two kinds of commands in C++ that alter the order in which statements are performed. Give some examples.

 

2.     In College algebra we see numeric intervals given as

2 < x < 3

Give the C++ Boolean expression that specifies that x lies between  2 and 3.

 

3.     Suppose Oliver Coder writes the following if statement:

 

if ( 2 < x < 3 )

cout << "true" ;

else

cout << "false" ;

 

Is this legitimate C++? If so, what is the output for each value of x:

 

x == 1, x == 2, x == 3 , x == 4

 

4.     Express the interval |x| > 1 as a C++ Boolean expression.

 

5.     Which of the following C++ expressions represents the interval mathematically represented as  

 

        1 < x < n?

 

a)  1 < x < n

b)  !(1 >= x >= n)

c)  !(1 > x || x > n)

d)  1 < x && x < n

e)  c and d

f)  a and b

 

6.     Given the expression

 

x + 1 > 2  ||  x + 1 < -3

 

which operations are done first, second, and so on. Either copy the expression and mark the operators to indicate the order, or fully parenthesize the expression to show the order of evaluation.

 

7.     Give a table of precedence rules for the unary operators, + - ++ -- and !, Boolean operators &&, ||, !=, ==, binary addition +, -, multiplication operators *, /, %, comparison ==, !=, and order operators <= >= > <.

 

8.     Describe  "short cut" evaluation.

 

9.     Does this code increment the variable i? Explain.

 

j = -1;

if ( j > 0 && i++ )

cout << i << endl;

 

10.   What is truth (true)? What is false? These are not philosopher's questions. Please answer these in the context of C++ Boolean expressions.

 

11.  Evaluate the following expressions. The value returned is either 1 or 0, which are interpreted as true or false by if, while, and for. You are to answer true or false, and explain.

 

The variables are assigned as follows.

 

limit = 10;

count = 0;

a)  (5&&8) + (!6)

b)  (limit < 0) && ((limit/count) > 7)

c)  ((limit/count) > 7) && (limit < 0)

d)  (limit < 20) || ((limit/count) >7)

e)  !(count == 12)

f)  (count == 1) && (x < y)

 

12.Some languages have built-in functions to determine whether an integer is odd. C++ does not. Write such a function in C++. This function returns an int that is either true (1) or false (0).

 

13.  Given the declaration and output statement. Assume that this has been embedded in a correct program and is run. What is the output?

 

enum Direction { N, S, E, W};

//...

cout << W << " " << E << " " << S << " " << N << endl;

 

14.  Given the declaration and output statement. Assume that this has been embedded in a correct program and is run. What is the output?

 

enum Direction { N = 5, S = 7, E = 1, W = 3};

//...

cout << W << " " << E << " " << S << " " << N << endl;

 

15.  In the following nested if statements there are two if keywords and one else. To which if does the else belong?

 

if ( x > y )

if ( u > v )

cout << 2 << endl;

else

cout << 1 << endl;

 

16.  Use parentheses to force the if-else binding suggested by the indentation.

 

if ( x > y )

if ( u > v )

cout << 2 << endl;

else

cout << 1 << endl;

 

17.  Describe the dangling else problem.

 

18.  What is the output from the following code, embedded in a complete program?

 

int x = 2;

cout << "start" << endl;

if (x <= 3)

if(x <= 3)

cout << "Hello from within second if" << endl;

else

cout << "Hello from within second else" << endl;

cout << endl;

cout << "start again" << endl;

if (x > 3)

if (x != 0)

cout << "Hello from the second if" << endl;

else   

cout << "Hello from the second else" << endl;

cout << "end again" << endl;

 

19.  NOTE: This question is about the differences in semantics between the switch and a nested if-else statement. These differences are subtle. This question is not explicitly discussed in the text.

 

 

Write the following switch statement as a nested if statement. Explain the (subtle) differences between the semantics of the if-else and the switch.

 

switch(vehicle)

{

case 1:

cout << "Passenger car.";

toll = 0.50;

break;

case 2:

cout << "Bus.";

toll = 1.50;

break;

case 3:

cout << "Truck":

toll = 2.00;

break;

default:

cout << "unknown vehicle";

break;

}

 

20.  What does a break; statement do? Where is it legal to put a break; statement;

 

21.   Suppose vehicle = 1, and the first break; is omitted from the code given here. In that event, what is the result of this code on the variable toll? What other effects may be observed?

 

switch(vehicle)

{

case 1:

cout << "Passenger car.";

toll = 0.50;

break;    // Suppose this break; is omitted.

case 2:   

cout << "Bus.";

toll = 1.50;

break;

case 3:

cout << "Truck":

toll = 2.00;

break;

default:

cout << "unknown vehicle";

break;

}

 

22.   What purpose does the default: clause in a switch statement serve?

 

23.  What is assigned to the variable x in each of these statements? What is the value of y after each statement is executed? These are not to be taken as having cumulative effect. Each statement begins with a value of y freshly assigned 3.

 

    y = 3;

 

a)   x = y++;

b)   x = ++y;

c)   x = y--;

d)   x = --y;

 

24.  What value results from execution of this code? Why?

 

int x = 1;

if ( x > 0 )

{

int x = 2;

x = x + 2;

}

else

{

int x = 3;

x = x + 2;

}

cout << x;

 

25.  A programmer wants to continue a loop provided the user has typed y or Y. Which of these are correct?

 

a)  while ( 'y' == ans || 'Y' == ans )

b)  while ( 'y' == ans )

c)  while ( 'Y' == ans )

d)  while ( 'y' == ans && 'Y' == ans )

e)  while (  y  == ans )

 

26.  Where could the following be a legal part of a C++ program?

 

while ( x > a );

 

a)     part of a while loop

b)    part of a do-while loop

c)     part of a for loop

d)    this always results in an infinite loop

e)     this is a loop without a loop body.

 

27.   Which of these are not differences between the do-while and while loops? (Mark all that are not differences, and mark the  incorrect statements.)

 

a)     the do-while loop tests at the bottom, while tests at the top

b)    the while loop tests at the bottom, do-while tests at the top

c)     the body of the while loop may not execute at all, the body of the do-while loop executes at least once

d)    while tests at the top, do-while at the bottom.

 

28.   The three looping constructs in C++ are ______________, ______________ and ______________.

 

29.  Give the output from the following loops? Assume these are embedded in a correct C++ program. Use these declarations.

 

int TRUE = 1;

int FALSE = 0;

 

a)  for( ; !TRUE; )

cout << 'X';

 

b)  int i = 1;

while(i <= 10)

{

if( i < 5 && i != 2 )

cout << 'X';

i++;

}

 

c)  for ( int i = 1; i <= 10; i = i + 3 )

cout << 'X';

 

d)  long m = 100;

do

{

cout << 'X';

m = m + 100;

} while( m < 1000 );

 

 

30.  Rewrite the following loops as for loops:

 

int TRUE = 1;

int FALSE = 0;

 

a)  while (!TRUE)

cout << 'X';

int i = 1;

while(i <= 10)

{

if( i < 5 && i != 2 )

 cout << 'X';

i++;

}

b)  int i = 1;

while (i <= 10)

{

cout << 'X';

i = i + 3;

}

c)  long m = 100;

do

{

cout << 'X';

m = m + 100;

} while( m < 1000 );

 

31.  Rewrite the following loops as do-while loops. Discuss.

 

int TRUE = 1;

int FALSE = 0;

 

a)  while (!TRUE)

i)  cout << 'X';

b)  int i = 1;

while(i <= 10)

{

if( i < 5 && i != 2 )

cout << 'X';

i++;

}

c)  int i = 1;

while (i <= 10)

{

cout << 'X';

i = i + 3;

}

d)  product = 1;

i = 1;

while (i <= 5)

{

product = product * i;

i++;

}

e)  long m = 100;

while (m < 1000)

{

cout << 'X';

m = m + 100;

}

 

 

32.  If these loops were embedded in a correct program, what would be the output?

 

a)  int c = 3;   

while( c-- > 0 )

cout << c << " ";

cout << endl;

 

b)  int c = 3;   

while( --c > 0 )

cout << c << " ";

cout << endl;

 

c)  int n = 1;

do

cout << n << " ";

while( n++ <= 3 );

cout << endl;

 

d)  int n = 1;

do

cout << n << " ";

while( ++n <= 3 );

cout << endl;

 

33.  What is the output of this loop? Identify the connection between the value of n and the value of the variable log.

 

n = 1024;

int log = 0;

for ( int i = 1; i < n; i = i * 2 )

log++;

cout << n << " " << log << endl;

 

34.  What is the output of this loop? Discuss.

 

n = 1024;

int log = 0;

for ( int i = 1; i < n; i = i * 2 );

log++;

cout << n << " " << log << endl;

 

35.   What is the output of this loop? Comment on the code.

 

n = 1024;

int log = 0;

for ( int 0 = 1; i < n; i = i * 2 )

log++;

cout << n << " " << log << endl;

 

36.   There are four methods for terminating an input loop. List them.

 

37.  Assume that a list has integers. Use the 'list headed by size'  method for terminating the input. Write a loop to sum the integers in the list. You need not prompt for input.

 

38.  Assume that a list has integers. Use the 'List ended by a sentinel' method for terminating the input. Use a -99999999 for a terminating sentinel. Write a loop to compute the product of integers in the list. You need not prompt for input.

 

39.  What is the most common error in designing and constructing loops?

 

40.  Discuss testing a loop, in connection with inputs that cause various numbers of iterations of the loop body.

 

41.  You have solved a problem. Your solution almost works in several respects, but you cannot determine why it fails. What may be the best tactic to obtain a correct solution to the problem?

 

42.  You have just tested completely and have found and repaired the 'last bug' in your latest program. How much testing should you do on this version?

 

43.  You have a fence that is to be 100 feet long. Your fence posts are to be placed 10 feet apart. How many fence posts do you need?  Why is this problem not as silly as it appears?

 

 

III. Part Three:

 

1.     Describe the difference in the meaning of int x[5]; and the meaning of 4 in x[4]. What is the meaning of the [5] and the [4]?

 

2.     True-False.  An array is a data type where the types of the elements may differ element to element.

 

3.     Multiple-choice: An array is accessed using

a)     the dot operator

b)    using an indexing operator square brackets

c)     using a member name

d)    none of the above.

 

4.     What could the following mean? You are to assume that this line of code is embedded in a correct, complete program. In particular, all identifiers have been defined.

 

Student ClassRoll[ 25 ];

 

5.     Declare   next,  and  max  to be int variables, and   score   to be an array of base type int having 5 elements,

 

a)     in separate statements,

b)    one statement,

 

6.     In the array declaration

 

double score[5];

 

what is

 

a)     the array name

b)    the base type

c)     the declared size of the array

d)    the range of values an index accessing this array can have

e)     one of the indexed variables (or elements) that of this array

 

7.     Identify any errors in the following array declarations. This code is assumed to be embedded in an otherwise correct and complete C++ programs.

 

a)  int x[4] = { 8, 7, 6, 4, 3};

b)  int x[] = { 8, 7, 6, 4};

c)  const int size = 4;

int x[size];

d)  const int size = 4;

int x[ size - 4 ];    

 

 

8.      What is the output of the following code (assuming it is embedded in a correct and complete program)?

 

char letter[4] = { 'a', 'c', 'e', 'g'};

for ( int i = 3; i >= 0; i-- )

cout << letter[i];

cout << endl;

 

9.     Consider the declaration

 

double a[10] = {1.2, 2.1, 3.3, 3.5, 4.5, 7.9, 5.4, 8.7, 9.9, 1.0};

 

Write a loop that will test this array for the condition

 

a[0] <= a[1] <= a[2] <= ...

 

Explain what you do to avoid out of bounds array access.

 

10.   Consider the declaration

 

double a[10] = {1.2, 2.1, 3.3, 3.5, 4.5, 7.9, 5.4, 8.7, 9.9, 1.0};

 

Write a function named  out_of_order  that takes as parameters an array of double and an int, size.  This function will test this array for being out of order, meaning that the array violates the condition:

 

a[0] <= a[1] <= a[2] <= ...

 

The function returns 0  if the elements are not out of order, and will return the index of the first element of the array that is out of order. For example, if a[2] and a[3] are the first pair out order, then a[3] is the first element out of order, so the function returns 3.

 

Take care with the loop control to avoid out of bounds array access, and explain what you did to avoid out of bounds array access..

 

11.  Assuming it is embedded in a complete, correct program, what is the output generated by this code fragment?

 

int member [10];

for (int i = 0; i < 10; i++)

member[i] = 10 - 2*i;

for ( i = 0; i < 10; i++ )

cout << member[i] << " ";

cout << endl;

 

12.   The following code has an error. Sometimes it reports that array element 10 is out of order for the following array. Sometimes it does not. Why?

 

//file: ch9tst9.cc

//test question

 

//The function returns 0 if the elements are not out of order, and it

//returns the index of the first element of the array that is out of order.

#include <iostream>

 

int out_of_order( double array[], int size )

{

int in_order = 1;

for( int i = 0; i < size ; i++)

if ( array[i] > array[i+1] )

return i+1;

return 0;

}

 

int main()

{

using namespace std;

double a[10] = {1.2, 2.1, 3.3, 3.5, 4.5, 7.9, 8.4, 8.7, 9.9, 10};

cout << out_of_order( a, 10) << endl;

return 0;

}

 

13.  Here is a function definition:

 

void doubler ( int& a )

{

a = a + a;

}

 

Given the following definitions, which of the following are correct?. If any one is not correct, explain what is wrong.

 

int a[4] = { 4, 5, 2, 3};

int number = 2;

 

a)  doubler ( number );

b)  doubler ( a[2] );

c)  doubler ( a[4] );

d)  doubler ( a[number] );

e)  doubler ( a );

 

14.  Consider this function declaration (prototype)  and function call:

 

int f( int& x, double y );

 

int main()

{

int u, v;

double w = 3.3;

u = f( v, w );

return 0;

}

 

Answer the questions, assuming the code above is completed by a definition of the function f.

 

a)     What are the formal parameters?

b)    What are the arguments? Give the correspondence between arguments and parameters.

c)     Which argument(s) may be changed by the call?

d)    Which local variable gets assigned?  With what value is it assigned, ?

e)     Which formal parameter is also a local variable of the function f? Describe the initialization of this variable.

f)      Which formal parameter of the function f is effectively a main program variable? How is this accomplished?

g)    Which parameter(s) are call-by-value and which are call-by-reference?

 

15.  What is different and what is the same for array parameters and a pass-by-reference parameters?

 

16.  Write a function named initialize and two lines of a main function to call this function. The two lines in main are a declaration of an array and the call to the function. You can use any legal array size in the call.

 

The function return type is to be void. There are two parameters one int array parameter and one int value parameter.  The function initializes the array elements all to 1.

 

 

17.  An array name, used as an argument in a call to a function, passes the _____________ ____  ______________ of the array argument to the formal parameter.

 

 

18.  Multiple choice: Which are correct, and why are the ones that are wrong incorrect? When a function having an array formal parameter is called, the formal array parameter

a)     names a copy of the array argument

b)    refers to exactly the same array as the calling program

c)     is passed the address of the argument, and the function needs further information about the array size to safely use an array parameter 

d)    refers to the array using a name that is always different from the calling program's argument.

 

 

19.   Here is a function that assigns a formal array parameter's members all to 1.

 

void initialize( int a[], int size )

{

for ( int i = 0; i < size; i++ )

a[i]= 1;

}

 

Write calls to this function initializing the specified array declared here.

a)     int a[5];

b)    int b[10];

c)     int c[15];

 

20.  When an array argument is passed to a function having an array parameter, exactly what is passed to the function? What is not passed to the function? What must be done about this lack of information?

 

21.  Explain the error in the following code. You may give the warning message, or error message, your compiler might give for the following error,  or you may describe the error. However you present the error, you must explain clearly what is wrong.

 

#include <iostream>

//Test question

void show_array( int ar[], int size )

{

using namespace std;

for ( int i = 0; i < size; i++ )

cout << ar[i] << " ";

cout << endl;

}

int main()

{

const int a[6] = { 2, 4, 2, 3, 5 };

show_array( a, 6 );

//...

}

 

22.  Consider the function definition and array declarations. Which are incorrect calls to the function make_4? Why?

 

(In considering this code, you are to ignore the a) b), and so on, at the start of the lines, and consider that this code is to be embedded in a complete and correct program.)

 

void make_4 ( int a[], int size )

{

for (int i = 0; i < size; i++ )

a[i] = 2;

}

 

int array1[20];

 

a)  make_4( array, 30 );

b)  make_4( array, 10 );

c)  make_4( array, 20 );

d)  "Hey, make_4, come change array1. Its size is 20."

 

int array2[50]; //A declaration for parts e) through h).

e)  make_4( array2, 50 );

f)  make_4( array2[], 50 );

g)  make_4( array2[5],50 );

 

23.  Describe the sequential search algorithm. In your discussion, mention what information the algorithm returns.

 

24.  What does the following code return?

 

int mystery ( const int a[], const int size, const int x )

{

for (int i = size - 1; i >= 0; --i)

if ( a[i] == x )

return i;

return -1;

}

 

25.  What does the following code return?

 

int mystery ( const int a[], const int size, const int x )

{

for (int i = 0; i < size; ++i )

if ( a[i] == x )

return i;

return -1;

a)     }

 

26.  What does it mean to "sort" an array?

 

27.  Describe or give pseudo code for the selection sort. The ideas are what is important for this question, not the coding details.

 

28.   Here is a list of 8 numbers. To sort these numbers, you are to use the selection sort algorithm. Fill in this table with each iteration of the loop in the selection sort algorithm. Mark the place from which you are looking for the 'next smallest element'. In this display, the upper numbers are the indices, the lower numbers are in the corresponding positions. Use the several rows provided to show the sequence of steps.

 

 

0 1      2       3       4        5       6      7

|------|-------|-------|------ -|-------|------|--------|------

  8   6      10      2        16      4       18      14     

 

 

 

0 1      2       3       4        5       6      7

|------|-------|-------|--------|-------|------|--------|------

 

 

 

0 1      2       3       4        5       6      7

|------|-------|-------|--------|-------|------|-------|------

 

 

 

0 1      2       3       4        5       6      7

|------|-------|-------|--------|-------|------|-------|------

 

 

 

0 1      2       3       4        5       6      7

|------|-------|-------|--------|-------|------|-------|------

 

 

 

0 1      2       3       4        5       6      7

|------|-------|-------|--------|-------|------|-------|------

 

 

 

0 1      2       3       4        5       6      7

|-----|--------|-------|--------|-------|------|-------|------

 

 

 

0 1      2       3       4        5       6      7

|------|-------|-------|--------|-------|------|-------|------

 

 

29.   Given the array declaration and code:

 

int a[10];

//code to initialize array a.

 

Write a function, index_of_smallest that takes an array parameter, an int parameter, size, and an int parameter start (a place  to start searching). The function finds the index of the smallest array element from start to the end of the array. Include preconditions and postconditions specifying any restrictions on parameters and what the output is to be. Use the const keyword for parameters appropriately.

 

30.   Consider these nested struct, class and array declarations.

 

struct S

{

int i[5];

double d[5];

};

 

class C

{

public:

);

//other constructors as needed

void f():         

private:

S s[10];

int i;

};

 

C c[5];

 

What type does each of the following objects have? Are there restrictions on what function may access any of these?

 

a)     c

b)    c[1]

c)     c[2].s

d)    c[2].i

e)     c[3].s[2]

f)      c[4].s[2].i

g)    c[4].s[2].d

h)    c[4].f()

 

31.  In the text , in the Case Study Problems and Programming Examples, there is a sequence of steps used. This is made explicit in this chapter for the first time. This sequence begins with "Problem Definition" and finishes with "Testing." List all the steps and explain what occurs in each of these steps.

 

32.   Write a code fragment that will find the index of the maximum and minimum elements in an array. Declare the array to have base type int.

 

33.  Which of the following statements about arrays is true?

 

a)     A function that has an array formal parameter knows nothing about the size of its array argument.

b)    It is legal to assign one array to another.

c)     You can initialize an array with an aggregate of constants enclosed in curly braces: { 12, 2, 4, -247 };

d)    There are only two times you can omit the size of an array: in a function declaration where you are specifying an array parameter, and when you have an array whose size is determined by the initializer list.

e)     The range of indices for an array are 0 up to and including the size of the array.

 

34.  In the linear (or sequential) search, how many comparisons are made:

 

a)     if the target of the search is not in the array?

b)    if the target of the search is in the index 0 position in the array?

c)     if the target of the search is in the index size - 1 position in the array?

d)    if the target is at index size/2?

 

Hint:  a linear search function is:

 

int search ( const int a[], const int size, const int x )

{

for (int i = size - 1; i >= 0; --i)

if ( a[i] == x )

return i;

return -1;

}

 

35.  You want to describe a game which requires 6 matches to constitute a game. In doing this you wish to declare an array Game of class Match of size 6.

First, write a class definition named Match, having member declarations of a default constructor, two access functions for the data variables, a void play function that has two char formal arguments,  home_play  and  opponent_play.  The class has two int data variables, home_score and opponent_score.

 

Now declare the array Game of class Match objects.

 

(You are NOT expected to implement the function members.)

 

 

ANSWERS TO REVIEW Problems

 

 

I. Part One Solutions:

 1.

a) double

b) double

c) illegal -- cannot use struct tag instead of a structure variable

d) illegal -- savings_account undeclared

e) char

f) CDAccount

2. structure value

3. collection

4. Many compilers emit poor error messages. Surprisingly, the error message from g++ is quite informative:

 

Borland C++ 5.4 for Win32

bcc32 ch6tstq4.cpp:

6: Too many types in declaration

7: Type 'A' may not be defined here

*** 2 errors in Compile ***

 

g++ -W -Wall --pedantic ch6tstq4.cpp

6: semicolon missing after declaration of `A'

7: extraneous `int' ignored

7: semicolon missing after declaration of `struct A'

 

In function `int main()':

8: warning: unused variable `struct A x'

 

5. A X = {1,2};

6.

a) Too few initializers, not an error. After initialization, month==12, day==21, year==0.

b) correct. after initialization, month==12, day==21, year==1995.

c) error: too many initializers

d) May be a design error, or an error in intent. The author of the code provides only two digits for the date. There should four digits allowed for the year, for the program could fail in ways that vary from amusing to disastrous at the turn of the century.

7.

67.5

21

195

166

8. jacket1:

S

46

s

$125.95

9. struct EmployeeRecord

      {     void setName(char[] _name)

            {    int length = 0;

    while (_name[length] != ‘\0’)  length++;    // find the length of the string “_name”

    for(int I = 0; I < length; I++)             // copy “_name” onto “name”

                  {     name[I] = _name[I];   }

                name[I] = ‘\0’;                             // string terminating character

             }

            void setWage(double _wage)

            {     wage = _wage ;   return;  }

            void setVacation(int _vacation)

            {     vacation = _vacation ;   return;  }

            void setStatus(char _status)

            {     status = _status ;   return;  }

            char[] getName()

            {     return name;  }

            double getWage()

            {     return wage;  }

            int getVacation()

            {     return vacation;  }

            char getStatus()

            {     return status;  }

 

 

    private:

      char[256] name;

            double wage;

            int vacation;

            char status;

      };

   EmployeeRecord SusanSample;

      SusanSample.setName(“Susan Sample”);

      SusanSample.setwage(60000.00);

      SusanSample.setVacation(15);

      SusanSample.setStatus(‘S’);

      cout << “Employee “ << SusanSample.getName() <<

            “ earns “ << SusanSample.getWage() << “ per year” << endl;

 

 

10. References:

a) gradebook.student_number

b) gradebook.midterm;

c) gradebook.exam

d) gradebook.quiz2

e) gradebook.grade

11. function:

void fix_exam_grade( Grades& gradebook_entry )

{

    gradebook_entry.exam = gradebook_entry.exam + 10;

}

12. function:

void read_grades( Grades& gradebook_entry )

{

    cout << "Enter student number, quiz average, midterm and "

         << "\nexam grades. Integers only please." << endl;

    cin >> gradebook_entry.student_number;

    cin >> gradebook_entry.quiz_average;

    cin >> gradebook_entry.midterm;

    cin >> gradebook_entry.exam;

}

13. For the purposes of the text, a struct has all public members that are data only, whereas a class may have data members or function members. The class's members are private, so inaccessible to any function except member functions of the class, unless declared to be public.

14.

a) s.x is legal. struct members are public unless otherwise specified.

b) c.x is illegal. class members are private unless otherwise declared public, unless used in a member function definition. No member function for class C are present.

c) d.x is legal. x is declared to be public within class D

d) c.z is illegal. All members of a class are private unless declared public, unless used in a member function definition. No member function for class C are present.

e) d.z is is illegal, unless this is in a definition of a member of class D. No member functions are present.

 

15. In a class definition, any function or data members, after a private: specifier can only be accessed from within the declaration of a function member of that class. Members following a public: specifier, and before any other specifier can be accessed from any function definition.

 

16. In defining a function that is declared (prototype occurs) in a class definition, one must put the definition in the scope of that class with this operator:

returned_ type class_ name:: function_ name( parameter_ list)

{

    // function body

}

 

17. At this point we are only defining the function. Member functions are intended to be used by any objects of the class DayOfYear, we have no way to know the name of any one that will be used, let alone all of them. We cannot provide the names. C++ knows when you call a function what the object is and arranges to use the data member belonging to that object, exactly as if we had preceded the member variable (or for that matter, a member function that might be used) by the object name.

 

18. True.

Example:

class MyClass

{

public:

    //constructor and other function members

    int member_func();

private:

    int data;

    //other data members

};

int MyClass::member_func() // member_func is associated with

{ //the class MyClass

    data = 0;

}

MyClass someObject;

int func()

{

    int z;

    z = someObject.member_func(); // member_func is associated

                                  // with class MyClass object

}                                 // someObject.

19.

void Temperature::set(double new_degrees, char F_or_C)

{

    degrees = new_degrees;

    scale = F_or_C;

}

 

20. False. Access to members declared in the private: section of a class, function or data, is granted to those functions declared anywhere in that class, public as well as private functions. Those denied access are functions declared anywhere else.

 

21. False. Access to members declared in the private: section of a class, function or data, is granted to those functions declared anywhere in that class, public as well as private functions. Those denied access are functions declared anywhere else.

 

22. True. Access to members declared in the private: section of a class, function or data, is granted to those functions declared anywhere in that class, public as well as private functions. Those denied access are functions declared anywhere else.

 

23. The client is more interested in the public members. The client cannot access the private members, and thus has no real (direct) use for them. Hence the public members should be placed first in a class.

 

24. A C++ class contains a complete list of all the functions that can access the private members of that class. This ensures complete control of the private data. This property is important for understanding a program in general. If the data were not private, the client programmer could corrupt the data in any way that the client sees fit. While this has considerable potential for mischief.

 

25.

a) Illegal. A::b is a private member of A, access denied in main.

b) Legal. A::increment_a() is a public member of A, access OK

c)Illegal. A::increment_b() is a private member of A.

d) Illegal. Cannot use == with classes.

e) Legal. A::get_a() is a public member

f) Illegal. A::get_b() is a private member.

g) Legal. Makes u contain the same data as v.

 

26.

a) A a; Illegal. No default constructor has been declared or defined

b) A a(1); Legal, calls A::A(int) constructor

c) int z = access_x(); Illegal, no object specified.

d) int z = a.x; Illegal, x is a private member of A

e) int z = a.access_x(); Legal, access_x() is a public member

 

27.

a) The only situation where the actual behavior and the appearance of the code may be different is a). Here, x is a function taking no arguments, returning an object of class A. This could be confused with a declaration of and A object initialized by the default constructor.

b) y is a class A object, initialized by the A::A(int) constructor.

c) z is a class A object, initialized by the A::A(int) constructor.

d)w is a class A object, initialized by the default constructor, A::A();

28.

a) This does not call a constructor

b) The compiler knows to call the A::A(int) constructor because it sees the int object as argument in the declaration.

c) This is an explicit call to the A::A(int) constructor. Same as b).

d) This is the proper syntax to invoke the default constructor for x to be a class A object, initialized by the

    default constructor.

 

29. A data type consists of a collection of values together with a set of basic operations defined on this set of operations values.

 

30. An ADT is a data type where the interface is separated from the implementation. The implementation details are hidden from the client.

 

31. False. A data type has two parts. One, the set of values, two the set of operations.

 

32. The member variables should be private. The collection of functions is the user interface. These should be public.

 

33. Helping functions have a potential for mischief. These should be private.

 

34. The member variables are part of the implementation. They are listed in the class definition for technical C++ reasons. All the function members have declarations (prototypes) and the explanations (except the helping functions) are part of the interface. All member function definitions are part of the implementation.

 

35. You need only read the interface parts. Specifically, you must read function declaration(s) (prototypes) in the class definition(s) and the commentary for these function members of the class(es). You can safely ignore the implementations of the function members, any private data members and any declarations (prototypes) of private function member functions.

 

 

 

II. Part Two Solutions:

 

1.     To this point we have studied selection statements, iteration statements, and function call statements. (Students may be aware of exception mechanisms and branching instructions which have not been studied at this point in the text.)

 

Examples of selection statements are if, if-else, and switch statements. Examples of iteration statements are while, do-while, and for statements.

 

2.  2 < x && x < 3.

 

3.      2 < x < 3 is legal. It does not mean (2 < x)&&(x < 3) as many would wish.  Rather, precedence rules  make this  mean (2 < x) < 3. Since (2 < x) is a Boolean expression, its value is either true or false. . which is converted to 0 or 1 when compared to 3. This in turn results in a comparison of 0 or 1 with 2,  so that  2 < x < 3 is always true.  The output is true regardless of the value of x.

 

4.   x > 1 || x < -1

 

5.     d

 

6.     Here is the fully parenthesized expression, with the order of operators marked:

 

 

 

7.  first: unary operators  + - ++ -- !

second: binary multiplication: * / %

third: binary addition:  + -

fourth: binary order   > < >= <=

fifth: binary compare   == !=

sixth: binary Boolean AND  &&

seventh: binary Boolean OR  ||

 

8.     Short cut evaluation occurs when the value of a Boolean operation can be determined from the first expression, as in

 

expr1 || expr2

 

if expr1 is true, the value of the OR expression is known to be true, there is no need to evaluate expr3, and C++ does not evaluate expr2.

 

9.     No. In the condition, j > 0 && i++, j > 0 is false (j was just assigned -1).  The && uses short circuit evaluation, which does not evaluate the second expression if the truth value can be determined from the first expression.  The first is false, the second does not matter.

 

10.  In the C++ language, for most compilers available, true and false are the constants of the bool type. In early compilers, 1 is  treated as true, 0 as false.

 

11.   

a)     true. (5&&8) evaluates to  true&&true, which is true. !6 evaluates to false, so the result is 1 + 0 == 1, which evaluates to true.

b)    false. limit < 0 is false, false && anything is false, the second expression is not evaluated, so the divide by zero is not encountered.

c)     error. produces a floating point exception on my machine (the problem is a divide by zero error)

d)    true. limit < 10 is true, short circuit evaluation result is true.

e)     false. count != 12 is true, !true is false.

f)      false. count == 1 is false, so expression is false, x<y is not evaluated.

 

12.int isOdd(int x)    // definition of odd is "leaves a remainder

{                      // of 1 after division by 2."

    return x%2;

}

 

13.    3 2 1 0

 

14.    3 1 7 5

 

15.  The else binds to the nearest previous if not already bound to an else, hence, the else belongs to the second if.

 

16.   The else binds to the nearest previous if not already bound to an else. Hence, the else belongs to the second if. The indentation suggests the else belongs to the first if. Group the second if and its statement with curly braces.

 

if ( x > y )

{

    if ( u > v )

        cout << 2 << endl;

}

else

    cout << 1 << endl;

 

17.  If there are several if keywords and fewer else keywords, the particular if that a particular else belongs may not be clear. C++ language requires that any else be bound to the nearest previous unbound if.

 

18.   

start

Hello from within second if

 

start again

end again

 

19.  The switch usually branches directly to the case, and with a break, branches to the end of the switch. The if executes each test until a successful if test  is found. The switch, if implemented correctly by the language implementor, may be very much faster than the nested if-else statement. The switch prohibits two case constants being equal. The nested if-else does not have this restriction.

 

The switch without the break allows fall-through to execute code. This can be simulated with a nested if-else statement only by duplicating portions of the case statement.

 

if (1 == vehicle)

{

    cout << "passenger car.";

    toll = 0.50;

}

else if (2 == vehicle)

{

    cout << "Bus.";

    toll = 1.50;

}

else if (3 == vehicle)

{

    cout << "Truck.";

    toll = 2.00;

}

else

    cout << "Unknown vehicle.";

 

20.  A break; statement is used to exit a loop: a while, do-while, or for statement, or to terminate a case in a switch statement. A break; is  legal any where else in a C++ program. Note that if the loops are nested, a break; only terminates one level of the loop.

 

21.  A $1.50 toll is assigned for both trucks and passenger cars. There is some warning of this, though, since if vehicle = 1, there are two messages displayed together: "Passenger car.Bus."  with no space between.

 

22.  The default: clause is the one chosen if no other case constant matches the value of the selector expression.

 

23.  The general principle is that prefix increment and decrement operators alter the value of the variable and return the altered value. The postfix increment and decrement operators return the original value, then alter the value of the variable.

 

y = 3;

a)  x = y++;  results in  x == 3, y == 4;

b)  x = ++y;  results in  x == 4, y == 4;

c)  x = y--;  results in  x == 3, y == 2;

d)  x = --y;  results in  x == 2, y == 2;

 

24.  1  The declarations within the {} are local to the blocks. They have no effect on the outer variable 

 

25.  a)

 

26.  b) part of a do-while loop.  Notes: a) b) and e) are syntactically correct answers, but a) implies e) and d). a) always results in d), an infinite loop. A loop without a body is legal, and is frequently used in a C/C++ idiom.

 

27.   b) is incorrect. All the rest are differences between while and do-while statements.

 

28.  for, do-while, while

 

29. 

a)  // there is no output from this loop

b)  XXX

c)  XXXX

d)  XXXXXXXXX

 

30. 

a)   

for ( ; !TRUE; )

cout << 'X';

b)  for ( int i = 1; i <= 10; i++)

if ( i < 5 && i != 2 )

cout << 'X';

c)  for ( i = 1; i <= 10; i = i + 3 )

cout << 'X';

d)  cout << 'X'; //necessary to keep output the same. Note

// also the change in initialization of m

for( long m = 200; m < 1000; m = m + 100 )

cout << 'X';

 

31.  This can be done with a 'kludge' where we prevent the do-while from executing the first time through. (A 'kludge' is a quick and ugly fix for a problem.)

 

a)  int first_time = 1;

do

{

    if( first_time )

        first_time++;

    else

        cout << 'X';

}while( !TRUE);

Ugly. I said it was an kludge, didn't I?

 

b)  int i = 1;  

do

{

    if ( i < 5 && i != 2)

        cout << 'X';

    i++;

} while( i <= 10 );

 

c)  int i = 1;

do

{

    cout << 'X';

    i = i + 3;

} while ( i <= 10 );

 

d)  product = 1;

i = 1;

do

{

    product = product * i;

    i++;

} while ( i <= 5 );

 

e)  long m = 100;

do

{

    cout << 'X';

    m = m + 100;

} while ( m < 1000 );

 

32. 

a)  2 1 0

b)  2 1

c)  1 2 3 4

d)  1 2 3

 

33.  output: 1024 10. The second number is the base 2 log of the first number.

 

34.  output: 1024 1. The ';' after the for is probably a pitfall error.

 

35.  This is an infinite loop. Notice that the update expression cannot do anything: it is i = i * 2, which leaves i at its initial value, 0.

 

36.  List headed by size: number of data to be input is known, a count controlled loop is used to obtain the data.

Ask before running the loop again

List ended with a sentinel value

Quit upon running out of input.

 

37.int x;    //data entry

int sum = 0;

int number;//number entries to be summed

cin >> number;

for ( int i = 0; i < number; i++)

{

    cin >> x;

    sum = sum + x;

}

// variable sum contains the sum of number data entries.

cout << endl << sum << endl;

 

38.int x=1; // data entry

int sum = 1;

int number; // number entries to be summed

do

{

    sum = sum * x;

    cin >> x;

} while ( x != -99999999 );

// variable sum contains the product of number data entries.

cout << endl << sum << endl;

 

39.  Off by one errors are the most common loop design errors.

 

40.  A loop should be tested with input that causes zero iterations, 1 iteration, one less than the maximum number of iterations, and the maximum number of iterations.  This is minimal. Several tests that relate to the specific problem that are between the maximum and minimum are also important to carry out.

 

41.  Discard bad programs that whose misbehavior baffles. Start over. Remember, the experience in attempting the solution will help in the second attempt.

 

42.  A full set of tests is appropriate for all but the most simple "hello, world" programs. You may have changed something that either causes another bug, or helps reveal another bug.

 

43.   Off by one errors abound in problem solving. Typical reasoning from those who do not think carefully is

 

a)     posts = 100 feet of fence/10 feet between posts. = 10 posts

 

This of course will leave the last 10 feet of fence without a post. You need 11 posts to provide 10 between-the-post 10 foot intervals to get 100 feet of fence.

 

 

III. Part Three Solutions:

 

1.      The statement, int x[5];, is a declaration, where 5 is the number of array elements. The expression x[4] is an access into the array defined by the previous statement. The access is to the element having index 4, which is the 5th (and last) array element.

 

2.     False. In an array, all the elements have the same type.

 

3.     Correct: b).  Wrong answers a) and c) are partial answers for struct and class member access.

 

4.     One might infer that the identifier, Student, is a type. Then ClassRoll is an array of size 25 of type Student. The code doesn't give any indication of what a Student might be.

 

5.   

a)  int next;

int max;

int score[5];

b)  int next, max, score[5];

 

6.   

a)  score

b)  double

c)  5

d)  0 - 4

e)  any of score[0], score[1], score[2], score[3], score[4]

 

7.      

a)     one too many initializers

b)    correct, array size is 4

c)     correct, array size is 4

d)    attempt to specify array size 0

 

8.     The output is  geca  followed with end-line.

 

 

9.              

for( int i = 0; i < 9; i++ )      //This is 9, not 10 because we are

if ( a[i] > a[i+1] )           //looking at a[i+1] for each i

cout  << "array elements " << index << " and "

<< index + 1 << " are out of order."

<< endl;

 

 

10.   

int out_of_order( double array[], int size )

{

int in_order = 1;

for( int i = 0; i < size - 1; i++) //This is size - 1 because

if ( array[i] > array[i+1] )  //we fetch a[i+1], for each i.

return i+1;         //Continuing up to size would

return 0;                //cause the element at index

}                     //size to be compared. This

//can cause erroneous results

//since we don't know what is

//in that location.

 

11.10 8 6 4 2 0 -2 -4 -6 -8

 

12.   This function compares array[i] > array[i+1] for each i from 0 to size - 1, hence it compares array[size-1] to array[size]. The 'element' at size is not in the array. The value there has no meaning for our program. If that value is smaller than the largest element in the array, the function will report the element size 'out of order'. If not, the function will report that the array is in proper order, and we will not find the error from this testing. 

 

What actually happens depends on what the was written in that memory location just before we read it.  Even if we test the routine with arrays that have out of order elements and with arrays that have no out of order elements, we may not discover this error.

 

Care is needed.

 

13. 

a)  doubler ( number );      //OK

b)  doubler ( a[2] );        //OK

c)  doubler ( a[4] );        //a[4] out of range, no warning or error.

d)  doubler ( a[number]);    //OK

e)  doubler ( a );           //Initializing non-const ‘int &’ with

  //‘int *’ will use a temporary, in passing

  //argument 1 of ‘doubler(int &)’

 

The warning in e) means that the compiler generates a temporary that is initialized, assigned, and discarded, with no change to the caller’s array argument.

 

14. 

a)  x and y

b)  v and w are arguments, v corresponds to x, w corresponds to y

c)  x can be change by the call.

d)  u is assigned the return value of the function f

e)  y is a local variable for the function f. y is initialized to a the value of the corresponding argument w.

f)  x is effectively the main program's variable v, as v uses x's memory location.

g)  x is a call-by-reference parameter, and y is a call-by-value parameter.

 

15.  An array formal parameter is called with an array argument, but the calling function knows only the base type of the array, but not the size. The array elements changed in the function result in the caller's argument array's corresponding elements being changed.

 

Every thing is known by the function about arguments that are passed to reference parameters. Changing a reference parameter changes the corresponding  arguments.

 

16.   A complete, tested program answering the problem is:

 

#include <iostream>

//file ch9tst16.cc

 

//Precondition: size is <= number of elements in the argument

//Postcondition: argument array element indexed from 0 to size - 1 are set to 1

void initialize( int a[], int size )

{

for ( int i = 0; i < size; i++ )

a[i]= 1;

}

int main()

{

using namespace std;

int x[10];

initialize( x, 10 );

for ( int i = 0; i < 10; i++ )

cout << x[i] << " " ;

cout << endl;

return 0;

}

 

17.  address in memory

 

18.  c) is correct. The rest are wrong, and here is why: a) suggests pass by value for arrays, b) suggests that the size of the array can be known by the calling function, d) suggests that we cannot use the same identifier in the formal parameter and the argument.

 

19. 

a)  initialize ( a, 5 );

b)  initialize ( b, 10 );

c)  initialize ( c, 15 );

 

20.  When an array argument is passed to a function having an array parameter, only the address of the first element is passed, and the declaration in the function header is all the function knows about the base type. Not even the base type is passed! In particular, the size is not passed, and is not known to the called function. The function author must write a parameter passing the size to the function.

 

The function whose array parameter is not declared const is called on the const int array a[6], producing the following warning (some compilers produce an error):

21.   

 

void show_array( int ar[], int size )

{               //^^^^ should be const for the call that follows.

//. . .

}

 

show_array( a, 5 );//warning: pointer to const given for

                     //argument 1 of 'void show_array(int*, int)'

 

The error message means that the compiler thinks the argument could be changed by the function, and considers this a violation of the programmer's promise not to change the array when the array was declared const.

 

22. 

a)  too large a size for array

b)  OK

c)  OK

d)  This is only a string, not a call!

e)  OK

f)  parse error before `]'

warning: passing integer to pointer argument 1 of

`void show_array(int *, int)' lacks a cast

 

23.  The sequential search algorithm in the text examines each array element in the order first to last to determine whether the target number is equal to any element in the array. The algorithm returns the index of the target, if present in the array, and -1 if the target is not present in the array.

 

24.  This code returns the index of the last member of the array a that is equal to x, and -1 if there is no member equal to x.

 

25.  This code returns the first member of the array that is equal to x, or -1 if there is no member equal to x.

 

26.  To "sort" an array means to reorder the elements of the array so that as the indices increase, the corresponding array elements increase:

 

a[ 0 ] <= a[ 1 ] <= a[ 2 ] <= ... <= a[ size - 1 ]

 

If the array elements are sorted decreasing, the array elements decrease as the indices increase.

 

a[ 0 ] >= a[ 1 ] >= a[ 2 ] >= ... >= a[ size - 1 ]

 

 

27.  selection sort

 

set the 'terminal segment of the array' to the whole array:

 

find the smallest element in the terminal segment of the array,

swap it with the index 0 element,

 

move the start of the terminal segment up to position 1,

find the smallest element in the terminal segment of the array,

swap it with the index 1 element,

 

move the start of the terminal segment up to 2,

find the smallest element in the terminal segment of the array,

swap it with the index 2 element,

 

(The algorithm continues in this manner until the array has been

sorted.)

 

Better:

Selection Sort:

terminal segment starts at element -1

while the terminal segment is not empty

{

move the start of the terminal segment up one element

find the smallest element in the terminal segment of the array,

swap it with the segment starting element

}

 

 

28.  Exercise the Selection Sort Algorithm:

 

X = start of terminal segment

 

0 1      2       3       4        5       6      7

X------|-------|-------|--------|-------|------|--------|------

  8   6       10      2        16      4       18      14

                     ^

smallest in the segment

swap with #0

move start of segment to index #1

0 1      2       3       4        5       6      7

|------X-------|-------|--------|-------|------|--------|------

  2   6       10      8        16      4       18      14

  ^

smallest in the segment

swap with #1

move start of segment to index #2

0 1      2       3       4        5       6      7

|------|-------X-------|--------|-------|------|--------|-------|

       2        4       10      8       16      6    18    14

                                ^

smallest in the segment

swap with #2     

move start of segment to index #3

0 1      2       3       4        5       6      7

|------|-------|-------X--------|-------|------|--------|------|

  2   4       6       8        16      10      18      14

  ^

smallest in the segment

swap with #3

move start of segment to index #4

 

0 1      2       3       4        5       6      7

|------|-------|-------|--------X-------|------|--------|-------|

  2   4       6       8        16      10      18      14

  ^

smallest in the segment

swap with # 4

move segment to index  #5

 

0 1      2       3       4        5       6      7

|------|-------|-------|--------|-------X------|--------|-------

  2   4       6       8        10      16      18      14

  ^

smallest in the segment

swap with # 5

move seg to index  #6

 

0 1      2       3       4        5       6      7

-------|-------|-------|--------|-------|------X--------|------

  2  4       6       8        10      14      18      16

  ^

smallest in the segment

swap with #6

move seg to index  #7

0 1      2       3       4        5       6      7

|------|-------|-------|--------|-------|-------|-------X------

  2  4       6       8        10      12       14      18

      ^

smallest in the segment

swap with #7

move seg to index  #8,

end of algorithm

29.   

//Precondition: declared size of array a >= size

//and 0 <= start and start <= size

//Postcondition: returns index of minimum element

//in array for indices  start through size.  

 

int index_of_smallest( const int a[], const int size, const int start )

{

int min = a[start];

int index_of_min = start;

for ( int i = start; i < size; i++ )

{

if ( a[i] > min )

{

min = a[i];      //min = smallest of a[k], 

index_of_min=i;  //for all k: start <= k <= i

}

}

return index_of_min;

}

 

30.   

a)  c  has array type with base type class C.

b)  c[1]  has type class C

c)  c[2].s  has array type with base type struct S. It is a private member of class C, hence is inaccessible outside a member or friend function of class C.

d)  c[2].i  has type int. It is a private member of class C. It is inaccessible outside a member or friend function of C.

e)  c[3].s[2]  has type struct S, an element of array s which is a private member or friend of class C, hence is inaccessible from outside a member function of C.

f)  c[4].s[2].i  has type int, a member of struct S, which is an element s, a private member of class C, hence it is inaccessible outside a member function of C.

g)  c[4].s[2].d has type double, a private member of class C, hence it is inaccessible outside a member function of C.

 

h)  c[4].f() has type function taking no arguments. It is a public member of class C.

 

 

31.   Steps: Problem Definition, Analysis of the Problem, Algorithm Design, Coding, and Testing.

 

a)     Problem Definition - Here we carefully review the problem statement. If we are being commissioned to solve a problem, we analyze the problem statement and carry any questions back to the person responsible for clarification. If we have difficulty with a problem set for us by Professor Z, we ask her for clarification. There should be specifications for the input format, the output format, and what the output should be in terms of the input. (Mathematicians like to say "the mapping of the input to the output."

 

b)    Analysis of the Problem. Here the problem is analyzed. (The roots of the word analysis is ana - to do again, lysis cut or loosen.) The problem cut apart several ways to determine the essential nature of the problem.

 

c)     Algorithm Design. By this time there should be sufficient understanding of the problem that an algorithm can be written.  The algorithm may be prepared in pseudocode.

 

d)    Coding. This should be the simplest part of the problem. The algorithm written in pseudocode is rewritten in C++.

 

e)     Testing. Full coverage testing is essential. Every branch of the if statements and each loop should be tested with data that causes limiting cases and several middle cases.

 

The text suggests that each program component should be debugged with a program that has been fully tested. This implies that functions that call other functions (main or other functions)  should be tested with stubs, (top down) and that bottom level subprograms ordinarily would be tested with drivers (bottom up.)

 

Finally,  it should be clear that this is an iterative process, i.e., that each of these steps may have to be repeated. We may begin with a first pass at a problem definition , think we understand the problem, until we do the analysis, then return to refine the problem statement. We may think we have the analysis correctly done until we try to create the algorithm. It may be necessary to refine both problem statement and the analysis. This continues until there is a satisfactory solution in hand.

 

32.int x[20] = { 3,4,3,54,3,6,4,3,2,2,3,-9,-987,5,4,56,6,8,987,6,};

int index_of_max, index_of_min, max, min, size = 20;

 

max = min = x[0];

for (int i = 1; i < size; i++)

{

if ( x[i] > max )

{

max = x[i];

index_of_max = i;

}

if ( x[i] < min )

{

min = x[i];

index_of_min = i;

}

}

 

33.   

a)     true.  You need to send the size into the function.

b)    Not on compilers that adhere to the standard. A few allow this (g++, for example).

c)     true.

d)    true. In the first case, you have to send the size in a separate parameter, and in the second, the size is determined by the number of initializers.

e)     false. the range is 0 up to and including (size - 1).

 

34.   

a)  number of comparisons = size

b)    1 comparison

c)  number of comparisons = size

d)  number of comparisons = size/2

 

 

35.class Match

{

public:

  Match();

  void play( char home_play, char opponent_play);

  int Home_Score ();

  int Opponent_score();

private:

  int home_score;

  int opponent_score;

};

 

Match Game[6];