UCLA PIC 10B,  Problem Solving using C++

Summer 2001,

Instructor: Ivo Dinov, Asst. Prof. In Mathematics/Neurology

# Midterm Exam Study Guide

## Thursday, July 19, 2001, 9:30 AM, PPB # 2214

Multiple choice questions may have more than one correct answer. Give all correct answers. If an answer to a multiple choice question is in some sense only partially correct, an explanation should be worth points. True - False questions require an explanation.

### I. Part One

1.     A string variable is the same thing as an  _ _ _ _ _   _ _   _ _ _ _ _ _ _ _ _ _.

2.     What is the length (maximum) of a string that can be placed in the string variable declared by the following declaration?  Explain.

char s;

3.

a)     What does the \ do in the null character '\0' or the newline character '\n'?

b)    What happens if you use a \w in an output statement?

4.     Give a declaration of a string s that is initialized in the declaration to the string "Happy Face :) ".

5.     How many characters are in each of the following character and string constants:

a)  '\n'

b)  'n'

c)  "Mary"

d)  "M"

e)  "Mary\n"

6.     Give the values for each character given the following string variable declaration. If an entry in the array is not given a value by the declaration, mention this.

char my_message = "Hi there";

7.     Declare a string named str capable of holding a string of length 10. Do not initialize it.

8.     Since character strings are just arrays of char, why does the text caution us not to confuse the following declaration and initialization?

char short_string[] = "abc";

char short_string[] = { 'a', 'b', 'c'};

9.     Given the declaration and initialization of the string variable:

char our_string = "Hi";

Write a loop to assign 'X' to all positions to this string variable, keeping the length the same.

10.  Given the declaration of a string variable, where SIZE is a defined constant:

char our_string[SIZE];

The string variable our_string has been set in code not shown here. For correct string variables, the following loop reassigns all positions of our_string the value 'X', leaving the length the same as before.

index = 0;

while (our_string[index] != '\0')

{

our_string[index] = 'X';

index++;

}

a)     Explain how this can destroy the contents of memory beyond the end of the array.

b)    Modify this loop to protect against inadvertently changing memory beyond the end of the array.

11.  Write code using a library function to copy the string constant "Hello" into the string variable declared here. Be sure to #include the necessary header file to get the declaration of the function you use.

char a_string;

12.   What is the output from this code segment, if embedded in a correct program and executed? Explain.

#include <cstring>

// whatever using directive that may be necessary

char a = "Hello";

char b = "Hi there";

if (strcmp( a, b ))

cout << "The strings are NOT the same";

else

cout << "The strings are the same";

cout << endl;

13.  Give declarations of char array variables of size 9 and 12. These declarations should initialize the arrays with the string constants "Hello" and "Hi there". Write code that outputs
"The strings are NOT the same" if the strings are different, and outputs
"The strings are the same" if the strings are the same.  Be sure to #include headers for any library function(s) you use.

14.  What dangers lurk in the use of functions declared in string? Give  an example.

15.  Describe the functions strlen, strcat, strcpy and strcmp. Give

a)     the arguments for each function

b)    the type of the return value for strlen and tell what this return value means.

c)     the type of the return value for strcmp and tell what this return value means.

d)    the action of strcpy

e)     the action of strcat

16.  Which of the following declarations are equivalent?

a)  char str = "Ahoy!";

b)  char str = { 'A', 'h', 'o', 'y','!', '\0'};

c)  char str = "Ahoy!";

d)  char str = { 'A', 'h', 'o', 'y','!'};

e)  char str[] = "Ahoy!";

17.  What string will be output when this code is run? (Assume, as always, that this code is embedded in a complete, correct program.)

char song = "I did it ";

char franks_song;

strcpy ( franks_song, song );

strcat ( franks_song, "my way!");

cout << franks_song << endl;

18.  What is the problem (if any) with this code?

char to_mia[] = "Frank sang, \" ";

strcat( to_mia, "I get along without you very well.");

19.  Suppose the function strlen were not already implemented for you in the library. Write a function definition for strlen. Remember that strlen takes only one argument, const char source[], and returns an int.

20.  Complete the dialog below when this code is run. You are to assume it has been embedded in a complete correct program.

char a;

cout << "Enter a line of input. " << endl;

cin.getline( a, 10);

cout << a << "<END OF OUTPUT" << endl;

Dialog:

Enter a line of input.

Do be do, do be do!

21.  Explain the getline member of the istream class.

a)     give the arguments (we know about two). What do the arguments do?

b)    give an example

c)     describe the behavior, specifically with regard where the input stops.

22.  Assume that line has been declared to be an array of char of size 80. Assume further that the file variable in_stream has been connected to a file infile.dat. Give code to read a line of data (or as much as will fit into the string variable line) from the file infile.dat into the string variable line.

23.  Given the declarations:

char number1[] = "3456";

char number2[] = "3.456e-7";

int n1;

double n2;

Provide the necessary header #include, and give a code fragment to translate the string

a)     number1 into an int value and assign it to n1,

b)    number2 into a double value and assign it to n2,

24.  Consider the following code. Assume it is embedded in a complete and correct program and then executed:

char my_string = "Enter a line of input\n";

cout << my_string;

cin.getline(my_string, 7);

cout << my_string << "<END OF OUTPUT" << endl;

If the dialog begins as follows, what is the output?

Enter a line of input:

May I get an ‘A’ in PIC10B.

25.  Declare a void function my_func that accepts an array declared as

int arr;

as one parameter. One other parameter is necessary. Give a function declaration (prototype) for this function. (Do not define it, you don't have enough information.)

26.  Write a code fragment that will prompt for and accept input to fill the array list (declared here) with 10 names typed in at the keyboard, assuming that the code you write is embedded in a correct, complete program.

char list;

27.  If the following code is embedded in a correct, complete program, it will fill the array list, declared here, with 10 names typed in at the keyboard.

char list;

int index;

cout << "Enter 10 names, one per line:" << endl;

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

cin.getline(list[index], 20);

What code can be added to this code fragment to output to the screen the first letter of each name, one letter per line?

28.  Assume this code fragment is embedded in a complete, correct program.  What is the output from this code fragment?

int array;

int index1, index2;

for (index1 = 0; index1 < 4; index1++)

for (index2 = 0; index2 < 4; index2++)

array[index1][index2] = index2;

for (index1 = 0; index1 < 4; index1++)

{

for (index2 = 0; index2 < 4; index2++)

cout << array[index1][index2] << " ";

cout << endl;

}

29.  Given the three String objects declared here. Give code using the class String members, concatenate word1 and word2 and assign them to phrase.

a)  String phrase, word1( "Mama " ), word2("mia!");

30.  Given the two String class objects declared here. The following use of overloaded operator+ from the String class to concatenate word1 and a blank ' ' is legal. Explain how this can be, since ' ' is not a String object.

String phrase, word1( "PIC10B" );

phrase = word1 + " ";

31.  Given the String class object declared here and the input statement:

String word;

cin >> word;

With the following input, what is place in the String object word? Why?

Mary was a little girl.

32.  Write code using the String class members from the text to read into  a string variable word all the characters from the input

String word;

Input:

Mary was a little girl.

33.  Consider the following partial String class definition. There is enough provided here for you to give a definition of the default constructor for this class.

const int MAX_STRING_LENGTH = 100;

class String

{

public:

String();

// initializes the object to the empty string;

...

private:

char character[MAX_STRING_LENGTH];

int current_length;

};

34.  Complete the definition of the member function String::set_char as declared here:

const int MAX_STRING_LENGTH = 100;

class String

{

public:

String();

// initializes the object to the empty string;

void set_char( int position, char new_char);

// Precondition: 0 <= position <= length

// where length is the value of calling_object.length()

// Action: Changes the character in position to new_char

// Notes:

// 1) the first character is in position 0.

// 2) You can set position to current_length

// which is one beyond the end of the string, adding

// one character to the end of the string.

...

private:

char character[MAX_STRING_LENGTH];

int current_length;

};

35.  Declare an array of 20 String objects named list. Write a code fragment to prompt for and accept 20 names, one per line.

36.  Declare an array of 20 String objects named list. Write a code fragment to prompt for and accept 20 names, one per line, then write code that will write the same names to the screen.

37.   Explain the definition of the multi-dimensional array int myIntArray3D; Order the indices fast-to-slow, elaborate on the very definition of a 3D array -  its meaning. If the address of the first element is in memory location 1000, compute the starting lication for the element myIntArray3D.

### II. Part Two

1.     Explain the concept of pointer in C++. Describe for the fact that objects occupy more than one memory address, e.g., an int type takes 4bytes=32bits(all of which are separate addresses.

2.      Give a declaration of a pointer to a double named double_ptr.

3.     What unfortunate misinterpretation can occur with the following  declaration?

int* int_ptr1, int_ptr2;

4.     This declaration can be misinterpreted to mean that both of these variables are int pointers. They are not. Give declarations that correctly declare these as int pointers. Hint: there are three that I can think of, one of which uses a typedef.

int* int_ptr1, int_ptr2;

5.     This declaration can be misinterpreted to mean that both of these variables are int pointers.  Show how to use typedef to have a declaration of these two that does declare these as int pointers.

a)  int* int_ptr1, int_ptr2;

6.     What is the type of each of the identifiers in the following declarations?

int * p1, p2;

7.  Declare v to be an int, and p to be a pointer to int, initialized in the declaration to point to v.

8.     Explain how an address can be an integer, a pointer is an address, but an address is not an integer.  Hint: This has to do with abstraction and the C++ type system.

9.     Give at least 3 uses of the & operator/symbol.  State what the & is doing, and  name the use of the & that you present.

10.  Give at least 3 uses of the * operator. State what the * is doing, and  name the use of the * that you present.

11.  What output does the following code produce?

int a = 0;

int *p = &v1;

*p = 49;

cout << a << endl;

cout << *p << endl;

12.  Make several drawings to illustrate the effect of these successive assignments given here. In particular, do not make ONE drawing then change that drawing.

Draw boxes for all these variables. Put int values in the boxes, and draw arrows to represent the values of the pointers to heap memory.

What untoward thing happens when the last assignment of pointers is made?

int *p1 = new int;

int *p2 = new int;

*p1 = 120;

*p2 =  60;

*p1 = *p2;

p1 = p2;

13.  Describe the difference between the effect of the following two assignments in the last two lines:

int * p1;

int * p2;

// code goes here to give p1 and p2 legitimate values

*p1 = *p2

p1 = p2;

14.  Describe the action of the new operator. What does the operator new return? What are the indications of errors?

15.  Write a code fragment that allocates memory on the heap (free store) for a variable of type int, and checks for error.

16.  You have a program that allocates memory on the heap (free store). What operator returns that storage to the heap (free store) for reallocation?

17.  What is a dangling pointer problem? What is the danger of dangling pointers?  What can you do to protect yourself against dangling pointers?

18.  Write a definition for a type called IntPtr that will be the type for pointer variables that hold pointers to dynamic variables of type int.  Write a declaration for a pointer variable named my_ptr which is of type IntPtr. Create a dynamic variable for this pointer.

19.  Write a code fragment that creates a dynamic array of int, that reads the size into your code fragment. Continue with code to fill each array position with an int equal to the its array index.

20.  Given the following code fragment, give code that destroys the dynamic array variable  a.

typedef int* IntArrayPtr;

IntArrayPtr a;

int array_size;

cin >> array_size;

a = new int[ array_size ];

21.   Assume the following code fragment is embedded in a complete correct program. If there is not enough memory in the heap (free store), the call to new will fail.  Give code that checks for this failure, and in the event of a failure, writes an error message to the screen, then exits the program.

typedef int* IntArrayPtr;

IntArrayPtr a;

int array_size;

cin >> array_size;

a = new int[ array_size ];

22.  Write a typedef statement for a type name, CharArray, for pointer variables that will be used to point to dynamic arrays having base type char.

23.  Given the following code that creates a dynamic array.

int * value = new int;

Write code that fills this array with 10 numbers typed in at the keyboard.

24.  Given the definitions:

int a;

int * p = a;

Which of the following is correct?

a)  *p is the same variable as a

b)  *(p + 2) is the same variable as a;

c)  p is a legal index operation.

d)  a++; is a legal operation.

e)  p++; is a legal operation.

25.  Given the code, which is assumed to be embedded in a correct and complete program:

int array_size = 10;

int a[array_size];

int * p = a;

int i;

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

a[i] = i;

What is the output of the following code fragment?

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

cout << p[i] << " ";

cout << endl;

a)     What is a destructor and what must the name of a destructor be?

b)    When is a destructor called?

c)     What does a destructor actually do?

d)    What should a destructor do?

e)

27.  Answer these questions about copy constructors.

a)     What is a copy constructor? What must its name be?

b)    When is a copy constructor called?

c)     What does a copy constructor actually do?

d)    What should copy constructor do?

28.

a)     If you do not provide a copy constructor, what happens when one is needed?

b)    If you do not provide an operator = overloading, what happens when one is needed?

c)     If you do not provide a destructor, what happens when one is needed?

29.  The following is the first line of the copy constructor definition for class StringVar. The identifier StringVar occurs three times. It means something slightly different each time. What does it mean in each of the three cases?

StringVar::StringVar( const StringVar& string_object)

30.  I want to overload the assignment operator, operator =. Can I make the operator= a friend of the class?

31.  Here is an attempt at defining operator = for the class StringVar that  has a bug when we try to assign a string to itself:

my_string = my_string;

Examine the code carefully and explain what the bug is.

void StringVar::operator= ( const StringVar & right )

{

delete [] value;

int new_length = strlen(right.value);

max_length = new_length;

value = new char [max_length+1];

if ( NULL == value )

{

cout << "error, insufficient memory " << endl;

exit(1);

}

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

value[i] = right.value[i];

value[new_length] = '\0';

}

### III. Part Three

1.     Explain in your own words what recursion means (in connection with definitions of  ideas and as a programming technique.)

2.     Any function whose definition contains a call to the function being defined is called a _______________ function.

3.     True of False: A recursive function must not return a value.

4.     How does the computer keep track of all the calls to a recursive function?

5.     Give a general outline of a successful recursive function definition.

6.     Describe the stack memory (or data) structure. Give a four-word description of the stack discipline.

7.     Why might a recursive solution to a problem run slower than an iterative version that does the same thing?

8.     Iterative solutions are always possible. Why then, would we bother with recursive solutions to problems? What advantages do some recursive algorithms have over the iterative versions?

9.  Here is a recursive function. Write an iterative version of it. Hint: Be sure you get the number of copies of "Hip" right.

#include <iostream>

void rec_cheers( int n )

{

using namespace std;

if ( 1 == n )

cout << "Hurray!" << endl;

else

{

cout << "Hip, ";

rec_cheers ( n - 1 );

}

}

10.  Here is an iterative function. Write a recursive function that does the same thing. Be sure you get right the number of times "Hip" is written. For this exercise you can ignore namespace issues.

void iter_cheers( int n )

{

for ( int i = 0; i < n-1; i++ ) // this is the tricky part!

{

cout << "Hip, ";

}

cout << "Hurray!" << endl;

}

11.  Write a recursive function that returns the sum of the members of an array of int numbers. Hint: For the recursive part, return the last element  +  the sum of the rest of the array. What should the base case be?

12.  Write a recursive void function that has one parameter which is a positive integer. When called, the function is to write its arguments to the screen backward: If the argument is 1234, the output should be.  4321.

13.  Write a recursive version of this iterative function:

int g( int n)

{

int h = 1;

int i = 0;

while ( i < n )

{

h = h * n;

h--;

}

return h;

}

14.  Here is a recursive function that is supposed to return the factorial.  Identify the line(s) with the logical error(s). Hint: This compiles and runs, and it computes something. What is it?

int fact( int n )         //a

{

int f = 1;     //b

if ( 0 == n || 1 == n ) //c

return f;        //d

else

{

f = fact(n - 1);     //f

f = (n-1) * f;      //g

return f;        //h

}

}

15.  Give the three criteria for a correct value returning recursive function.

16.  Give the three criteria for a correct recursive void-function.

17.  In the binary search, if the array being searched has 32 elements in it, how many elements of the array must be examined to be certain that the array does not contain the key? What about 1024 elements? Note: the answer is the same regardless of whether the algorithm is recursive or iterative.

18.  Overloading and Recursion look to be similar. Both situations call functions with the same name.  Explain the difference.

19.  In the binary search, each pass (recursion or iteration) selects a subproblem of the original problem to solve. What fraction the array sent to an initial call is eliminated in the next iterative pass or recursive call?

20.  Give a pseudo-code description of the recursive binary search algorithm.

21.  In both the iterative and the recursive binary search, explain why the condition for halting the routine with the variable found assigned false is first > last.

22.  The form of recursion where the recursive call is the last statement executed by the function is called _ _ _ _ recursion.

23.  The part of a recursive function definition where that does not lead to the function calling itself is called the _ _ _ _ case or _ _ _ _ _ _ _ _ _ _ _ part.

24.  What is the output of this recursive program?

#include  <iostream>

void recursive( int i )

{

using namespace std;

cout << i << " ";

if ( i < 8 )

{

i++;

recursive(i);

}

}

int main()

{

using namespace std;

recursive(3);

cout << endl;

}

25.  Write an iterative version of this recursive function.

void recursive( int i )

{

using namespace std;

if ( i < 8 )

{

cout << i << " ";

i++;

recursive(i);

}

}

26.  How many times is the following code invoked by the call recursive(4)?

a)  2

b)  4

c)  8

d)  32

e)  this is an infinite recursion.

void recursive( int i )

{

using namespace std;

if ( i < 8 )

{

cout << i << " ";

recursive(i);

}

}

27.  What is the output of the recursive function below when called with an argument of 5?

a)  6 7 8

b)  5 6 7

c)  8 7 6

d)  7 6 5

e)  None of these. This is an infinite recursion if the function is called with argument 5.

void recursive( int i )

{

using namespace std;

if ( i < 8 )

{

i++;

recursive(i);

cout << i << " ";

}

}

28.  True or False: Each recursion causes a new activation frame to be placed on the stack.

29.  True or False: Each activation frame contains all the function’s code, as well as the automatic variables and formal parameters.

30.  True or False: The activation frames in nested function calls are handled in a last-in/ first-out manner.

========================================================================