Sei sulla pagina 1di 4

MIT OpenCourseWare

http://ocw.mit.edu

6.096 Introduction to C++


January (IAP) 2009

For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
MASSACHUSETTS INSTITUTE OF TECHNOLOGY

6.096: Introduction to C++ IAP 2009


PROBLEM SET 4

Initializing multidimensional arrays:


The examples of multidimensional arrays in lecture did not give the syntax for initializing them. The way
to assign a multidimensional array in the array declaration is as follows:

int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };

Inside the inner braces, commas still separate individual numbers. Outside, they separate rows of the
array. After this declaration, matrix[0][1] will return the value 2.

Each one of the rows is initialized like a regular array. For instance, if instead of {1, 2, 3} we’d put
{1}, the second and third elements of the first row would have been initialized to 0.

1. Write a program that declares the 2D array of student test grades shown below, and stores the
students’ averages in a 1D array. Each row in the 2D array represents the grades of a particular
student (their parents uncreatively named them Student 0, Student 1, etc.). Output the array of
averages.

int studentGrades[6][5] = { {97, 75, 87, 56, 88}, {76, 84, 88, 59, 99},

{85, 86, 82, 81, 88}, {95, 92, 97, 97, 44}, {66, 74, 82, 60, 85}, {82,

73, 96, 32, 77} };

Multidimensional arrays as arguments:


The syntax for passing multidimensional arrays as arguments is very similar to that of passing regular
arrays. The main difference is that you need to include the number of columns in the function definition.
For instance, a function that takes a 2-dimensional array with 3 columns might be declared as follows:

void func( int array[][3], const int rows, const int columns ) {…}

2. Write a function based on your program from question 1 to calculate a set of grade averages. It
should take a few arguments, including a 2D array of student grades and a 1D array to store the
averages in. (Recall that arrays are passed by reference.) It should return nothing.

3. Multidimensional arrays are often used to store game boards. A tic-tac-toe board is a basic
example: the board can be stored as a 2D array of integers, where a positive number represents
Player 1, a negative number represents Player 2, and 0 represents a space not yet taken by either
player. Write a void function printTTTBoard that takes such a 2D array as an argument and
prints the board as a series of X’s, O’s, or spaces, separated horizontally by tabs and vertically by
newlines. For instance, it should output the following board for the array
{ {0, -1, 1}, {-1, 1, -1}, {-1, 1, 1} }:
O X

O X O

O X X

4. Assume that the following variable declaration has already been made:

char *oddOrEven = "Never odd or even";

Write a single statement to accomplish each of the following tasks:


a. Print the 4th character in oddOrEven
b. Create a pointer to a char value named nthCharPtr that stores the memory address of
the 4th character in oddOrEven
c. Using pointer arithmetic, update nthCharPtr to point to the 7th character in oddOrEven
d. Print the value currently pointed to by nthCharPtr
e. Create a new pointer to a pointer (a char ** – yes, those are legal too!) named
pointerPtr that points to nthCharPtr
f. Print the value stored in pointerPtr
g. Update nthCharPtr to point to the next character in oddOrEven (i.e. one character past
the location it currently points to)
h. Using pointer arithmetic, print out how far away from the character currently pointed to
by nthCharPtr is from the start of the string

5. Write a function swap that takes two arguments – pointers to character values – and swaps the
values of the variables these pointers point to. It should return nothing.

6.
a. Write a function reverseString that takes one argument – a C-style string (a char *)
– and reverses it. The function should modify the values of the original string, and
should return nothing. (You may assume that you have a properly implemented swap
function as described in the previous problem. You may also use the strlen function,
which takes a char * and returns the length of the string. It is found in the cstring
standard header file.)

b. Indicate with two lines of code how you would declare a character array (a char[], not a
char*) containing the string "aibohphobia", and reverse it using reverseString.

Function pointers:
We mentioned in lecture that, since functions are really just blocks of instructions in memory, you can
create a pointer to a function. Schematically, the syntax for declaring such a pointer is as follows:

return_type (*name)(argument_types);

The syntax for declaring the pointer is identical to the syntax for declaring a function, except that where
you’d put the name of the function in the function definition, you put (*pointerName). To give an
example:
void (*functionPtr)(int, char) = &someFunction; // & is optional

Here, we declare a function pointer named functionPtr which points to some function named
someFunction. That function must be a void function that takes as arguments one int and one char.
Once we’ve declared functionPtr as a function pointer, we can use it to call the function it points to
simply by writing something like functionPtr(1, 'a').

7.
a. Define two functions, cmpAscending and cmpDescending. Each should take two
integers. cmpAscending should return true if the first integer is greater than the second
and false otherwise. cmpDescending should do the reverse. Each one should be no
more than 3 lines of code.

b. One common application of function pointers is sorting – you can pass a function pointer
to a sorting function to decide whether to sort in ascending or descending order. Extract
the nested loop from the bubble sort code snippet from the Lecture 4 notes and place it
into its own function. The function should take 3 arguments: an integer array, the length
of the array, and a function pointer. The function pointer (call it comparator) should be
of a type that points to a function that takes two integers and returns a boolean. Modify
the sorting code snippet to use comparator to compare values for sorting, and show
how you’d call your sort function with either cmpDescending or cmpAscending.

8. Write a line to accomplish each of the following tasks. You will want to look up the
documentation for string functions online. (Recall that the way to call a function on a string
variable is, for instance, myString.find("a"). Also note that the usual cin and cout
syntaxes work for strings, but cin will stop reading at the first whitespace character.)
a. Declare a variable papayaWar of type string (assuming header file <string> has
been included). Initialize it to the value "No, sir, away! A papaya war is on!"
b. Print the index of the first instance of the exclamation point character in papayaWar.
c. Print the length of the papayaWar string.
d. Print the last 5 characters of papayaWar.
e. Replace the contents of the string with a string that the user enters.
f. Append the string "rotator" to the end of papayaWar.
g. Print the contents of papayaWar.

Potrebbero piacerti anche