CS117 Midterm 2, Fall 1999 CS 117
Midterm 2
Ondich
Due ON PAPER 8:30 AM Monday, November 15, 1999

This is an open book, open notes, and open computer test. You may not use any books other than your textbook, and you may not use Internet resources from off campus. If you get stuck, talk to Jeff Ondich, but please don't talk to anyone else about the exam.

Provide brief, clear justification for your answers.

This exam has a time limit, of sorts. You may think about it all you like, with or without paper and textbook at hand. But don't use more than 5 hours combined working at the computer and writing up your answers.

  1. (8 points) What output does the following code produce? Why?

    
    	short k = -32768;
    	k = k * -1;
    	cout << k << endl;
    

  2. (15 points) I have N numbers stored in an array a[], and I want to know the distance between the pair of these numbers that are furthest apart. Elmo suggests the following code, which does the job:
    
    	int max = 0;
    	for( int i=0; i < N; i++ )
    	{
    		for( int j=0; j < N; j++ )
    		{
    			if( a[i] - a[j] > max )
    				max = a[i] - a[j];
    		}
    	}
    

  3. (15 points) The program sierpinski.cpp draws a picture. Try it out, and then answer the following questions.

  4. (3 points) I would be much obliged if you would recommend a book for me to read.

  5. (12 points) Consider the weird little program sesame.cpp.

  6. (The longest 5-point question in history) Suppose you define the following struct:

    
    const int maxNameLength = 50;
    
    struct Person
    {
    	char		name[maxNameLength+1];
    	int			heightInInches;
    	int			numberOfPets;
    
    	// More stuff if you feel like it.
    };
    

    C++ allows you to assign one Person variable to another. For example, to sort a collection of Person structs, you might use code like this:

    
    void SelectionSort( Person p[], int nPeople )
    {
    	...
    
    		Person temp;
    		
    		temp = p[indexOfMax];
    		p[indexOfMax] = p[i];
    		p[i] = temp;
    
    	...
    }
    

    That is, even though C++ doesn't have the Person type built in to it, the compiler can arrange for the program to copy one Person variable to another, simply by copying the struct one byte at a time. That's nice, and helps make thinking abstractly using structs and classes easy.

    Here's the weird thing. You can't compare structs like this:

    
    	Person	a, b;
    
    	...
    
    	if( a == b )
    	{
    		// Do something
    	}
    	else
    	{
    		// Do something else
    	}
    

    This code simply won't compile. But why not? If the C++ compiler is happy to let you copy one struct to another, byte for byte, why won't it let you compare two structs with one another, byte for byte? For what reason would the designers of the C++ language want to avoid letting you test two records for equality in this way?