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:

{

int student_number;

int quiz1;

int quiz2;

int midterm;

int exam;

};

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

a) the student number

d) the grade on the second quiz

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.

{

int student_number;

int quiz_average;

int midterm;

int exam;

};

//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.

{

int student_number;

int quiz_average;

int midterm;

int exam;

};

//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 ];

e)  int size;                //To the instructor: This question

cin >> size;                //considers a point not extensively

int x[ size ];        //discussed in the text. I think it worth

//mentioning, but you may wish to omit this

//part of this question.

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.)