=========================preview======================
(COMP103)final05.pdf
Back to COMP103 Login to download
======================================================
Hong Kong University of Science and Technology
COMP104: Programming Fundamentals and Methodology

Fall 2005, Lecture Section 1, 2, 3
Final Examination
Tuesday, Dec.20, 2005 16:30 C 19:30

Student Name: key Lecture Section:


Student ID: Lab Section/TA Name:

Instructions:

1.
This is a closed-book, closed-notes examination, calculator is also not allowed.


2.
Use pen only (no pencil).


3.
Write your name, student ID, lecture section, lab section and 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
Topic
Score

1
File I/O
/4

2
Pointers
/6

3
Dynamic Objects
/14

4
Struct
/10

5
Simple Linked Lists
/13

6
Algorithms on Linked Lists
/12

7
Circular and Doubly Linked Lists
/8

8
Class
/5

9
ADT
/9

10
Dynamic Class
/10

11
Stack
/9

Total
/100




Question 1: File I/O (4 marks)




The following program is supposed to read in a file in.txt and display it to the screen. Fix any bugs.

1 #include <iostream>
2 using namespace std;

3 void main(){
4 char c;
5 ifstream fin(in.txt);
6 while(true){
7 fin.put(c);
8 if(!fin.eof())
9 break;
10 cout << c;
11 }
12 fin.close();
13 }

Answer (1 mark each):
(1) Need: #include <fstream>
(2) in(in.txt);
ifstream f should be:
ifstream fin;
fin.open(
"in.txt"); (3) fin.put() should be fin.get()
(4) !fin.eof() should be fin.eof()



Question 2: Pointers (6 marks)
a)
What is the output of the following program? (4 marks)

#include <iostream>
using namespace std;
void swap1(int* p,int* q)
{
int* temp;
temp = p;
p = q;
q = temp;
}
void swap2(int& a,int& b)
{
int temp;
temp = a;
a = b;
b = temp;
}
int main()
{
int a = 1,b = 2;
int *p = &a, *q = &b;
swap1(p,q);
cout << *p << ' '<< *q << endl;

swap2(a,b);
cout << *p << ' '<< *q << endl;
return 0;
}



Answer:
1 2 (2 marks)
2 1 (2 marks)




b)
What is the output of the following program? (2 marks)

#include <iostream>
using namespace std;
int main()
{
int a[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
int *p;
p = *(a+1)+2;
cout << *p;
return 0;
}



Answer: 6




Question 3: Dynamic Objects (14 marks)
a) There is no compilation error in the following program. However there is a memory problem. What is the name of it? (2 marks)

#include <iostream>
using namespace std;

void main(){
int *a;
int *b;
b = new int;
*b = 7;
a = new int[*b];
a = b;
b = a;
}

Answer:
memory leak (2 marks)




b) There is no compilation error in the following program. However there is a memory problem. Wh