=========================preview======================
(COMP104)final02.pdf
Back to COMP104 Login to download
======================================================
Hong Kong University of Science and Technology
COMP104: Programming Fundamentals and Methodology
Fall 2002, Lecture Section 1, 2, 3, 4
Final Examination
Friday 20 December, 08:30 - 11:30AM
Student Name: key Lecture Section:
Student ID: Lab Section/TA Name:
Instructions:
1.
This is a closed-book, closed-notes examination.
2.
Check that you have all 18 pages (including this cover page).
3.
Write your name, student ID, lecture section, lab section/TA name on this page.
4.
Answer all questions in the space provided. Rough work should be done on the back pages.
Question
Score
1
/5
2
/2
3
/5
4
/5
5
/5
6
/31
7
/8
8
/5
9
/16
10
/7
11
/5
12
/6
Bonus
( /3)
Total
/ 100
Question 1: Dynamic Objects and Arrays (5 marks)
The following program is supposed to allocate and read in a dynamic matrix of doubles, and print out the transpose of the matrix. Only 1-D arrays can be allocated dynamically, so a simulated 2-D matrix is used (we can represent A[i][j] by B[i*dim2+j], where dim2 is the second dimension of A[dim1][dim2]). Fix any bugs in the program. Here is an example of running the program:
Input number of rows: 2
Input number of columns: 3
Input matrix:
1 2 3
4 5 6
Transpose of matrix:
1 4
2 5
3 6
Line No.
1
#include <iostream>
2
using namespace std;
3
int main( ){
4
int nrows, ncols, r, c;
5
double a;
6
cout << "Input number of rows: ";
7
cin >> nrows;
8
cout << "Input number of columns: ";
9
cin >> ncols;
10
a = new double[nrows];
11
cout << "Input matrix: " << endl;
12
for(r=0; r<nrows; r++)
13
for(c=0; c<ncols; c++)
14
cin >> a[r*ncols+c];
15
cout << "Transpose of matrix: " << endl;
16
for(c=0; c<ncols; c++)
17
for(r=0; r<nrows; r++)
18
cout << a[c*nrows+r] << " ";
19
return 0;
20
}
Answer: (5 marks)
double* a; // Line 5: 1 mark
a = new double[nrows*ncols]; // Line 10: 1 mark
cout << "Transpose of matrix: " << endl;
for(c=0; c<ncols; c++){ //
for(r=0; r<nrows; r++)
cout << a[r*ncols+c] << " "; //L18: 2 marks
cout << endl; // insert after L18: 1 mark
}
(-1 for any added bug)
Question 2: Characters (2 marks; 1 mark each)
What is the output after executing the following C++ statements?
(a)
int n = 0;
if('A' == 'a')
n = 1;
else if('A' > 'a')
n = 2;
else
n = 3;
cout << n << endl;
Answer:
(b)
int n = 0;
char c1 = 'g', c2 = '6';
char c3 = toupper(c1);
if(isdigit(c2))
if(islower(c3))
n = 1;