=========================preview======================
(COMP152)[2009](f)midterm~ma_yxf^_10142.pdf
Back to COMP152 Login to download
======================================================
THE HONG KONG UNIVERSITY OF SCIENCE & TECHNOLOGY
Department of Computer Science & Engineering
COMP 152: Object-Oriented Programming and Data Structures
Fall 2009
Midterm Examination
Gary Chan
Date: Saturday, October 24, 2009 Time: 10:00am C 11:45am
Place: LT-D
.
Your answers will be graded according to correctness, ef.ciency, precision, and clarity.
.
This is a closed book examination. Put aside your calculators, cellphones, PDAs, Palms, etc.
.
This booklet has 20 single-sided pages. Please check it.
.
You may use the reverse side of the pages for your rough work or continuation of work.
Student name: English nickname (if any): Student ID: Email address:
I have not violated the Academic Honor Code in this examination (your signature):
Question
Your score
Maximum score
1
15
2
30
3
25
4
30
TOTAL
100
1. Basic C++ Features (15 points)
(a) (5 points) Please write down the output of the following codes:
void f1(int * var){
*(var+4)= 50;
}
void f2(int & var){
var= 500;
}
void f3(int var){
var= 5000;
}
void print(int * a){
for(int i=0; i<5; i++)
cout<<a[i];
cout<<endl;
}
int main(){
int a[5]= {1,2,3,4,5};
print(a);
f1(a);
print(a);
f2(a[4]);
print(a);
f3(a[4]);
print(a);
return 0;
}
(b) (10 points) Consider the following recursive codes on the function foo:
#include <iostream>
using namespace std;
void swap(int & a, int & b){
int temp = a;
a =b;
b = temp;
}
void foo(int * a, int n){
int x = (n+1)/2;
if(x ==1 )
return;
else
for(int i=1; i<x; i++)
if(a[0] < a[2*i])
swap(a[0], a[2*i]);
foo( &a[1], n-1);
}
int main(){
int a[4]={4,2,7,1};
foo(a , 4);
for(int i=0; i<4; i++)
cout<<a[i];
cout<<endl;
return 0;
}
i. (7 points) What is the output for the above code?
ii. (3 points) Please brie.y state what the function foo(a, n)does to the array aof size n.
2. Basic Class Implementations (30 points)
In this problem, you are to implement a class gridNdwhich represents a N -dimensional grid point (x0 ,x1 ,x2 , ..., xN .1 ). The dimension of the point is stored in data member int dimension, and the value of xi is stored in data[i], where 1 i N . 1.
The following is the declaration of gridN:
class gridNd {
public:
gridNd(); //default constructor
gridNd(const gridNd& g); //copy constructor
gridNd(int x); //conversion constructor
.gridNd(); //destructor
gridNd & operator=(const gridNd & g); //assignment operator
private:
int *data; // the coordinate xis
int dimension;
};
You are to write down various member functions for gridNd.
(a) (5 points) Please implement the default constructor:
// default constructor.
// Create a default 2-dimensional point (0,0)
gridNd::gridNd ()
{
// first cout the type of constructor
cout<<"default constructor"<<endl;
// implement your codes below
(b) (5 points) Implement the copy constructor:
/