=========================preview======================
(COMP104)[2003](s)final~ycchak^_10126.pdf
Back to COMP104 Login to download
======================================================
Hong Kong University of Science and Technology
COMP104: Programming Fundamentals and Methodology

Fall 2003, Lecture Section 1, 2
Final Examination
Wednesday 17 December, 4:30 C 7:30PM

Student Name: Lecture Section:

Student ID: key Lab Section/TA Name:

Instructions:
1.
This is a closed-book, closed-notes examination.


2.
Check that you have all 19 pages (including this cover page).


3.
Write your name, student ID, lecture section, lab section/TA name on this page.


4.
Please circle your answer.


5.
Answer all questions in the space provided. Rough work should be done on the back pages.




Question
Score

1
/6

2
/5

3
/4

4
/8

5
/3

6
/5

7
/3

8
/4

9
/8

10
/7

11
/6

12
/10

13
/4

14
/17

15
/10

Total
/100







Questions 1 & 2 C Pointers

Question 1: (6 marks)
a) (4 marks) What is the output of the following program?
#include <iostream>
using namespace std;
void main( ){
int a[3] = {1, 3, 5 }, b = 23, c = 48;
int *p1 = a,
*p2 = &b,
*p3 = 0;
p1++;
(*p1)++;
p3 = p2;
*p3 = p1[1];

for(int i = 0; i < 3; i++)
cout << a[i];
cout << endl;
cout << b << endl;
}
Answer:
145 (1 mark for each digit)
5

b) What is the output of the following program? (2 marks)
#include <iostream>
using namespace std;

void swap(int* left, int* right) {
int* p;
p = left;
left = right;
right = p;
}

void main( ){
int a = 3, b = 5;
swap(&a, &b);
cout << a << " " << b << endl;
}
Answer:
3 5 (1 mark each)
Question 2: (5 marks)

Please fill the blank part of the following code. Your task is to store the data of 2D array A to 1D array P. Important: You must use pointer arithmetic to access the values of P instead of subscripts.

#include <iostream>
using namespace std;
const int m = 3;
const int n = 5;
void main( ){
int A[m][n] = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15}
};
int i, j;
int * P = new int[m * n];

// Store the data of 2D array a[3][5] to 1D array P[15]
// Add your code below







// ------------------------------------------

for(i = 0; i < m*n; i++)
cout << P[i] << " ";
cout << endl;
}
Answer:
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
*(P + i*n + j) = A[i][j];

-1 for each mistake , -2 if P[i*n+j] = A[i][j]
-2 if the arithmetic formula P+i*n+j is incorrect

Questions 3 & 4 C Dynamic Objects

Question 3: (4 marks)
What is wrong with the following code?

#include <iostream>
using namespace std;
1 int main() {
2 int a = 5, *p = &a;
3 int *q = new int ;
4 *q = *p;
5 cout << a << << *p << << *q;
6 delete p;
7 return 0;
8 }
Answer:
2 marks - The memory unit pointe