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

Fall 2001, Lecture Section 1, 2, 3, 4
Midterm Examination
Tuesday 23 October, 7 C 9PM

Student Name: Lecture Section:


Student ID: Lab Section/TA Name:

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


2.
Check that you have all 16 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
/4

3
/5

4
/4

5
/2

6
/2

7
/8

8
/5

9
/6

10
/3

11
/8

12
/6

13
/12

14
/7

15
/6

16
/10

17
/6

Total
/100







Question 1: Basic expressions (6 marks: 2 each)

Transform the following mathematical expressions into valid C++ expressions:

a)
A Boolean expression: 10



b)
An arithmetic expression (including predefined mathematical functions): )1()



c)
An arithmetic expression:








Key:

a) 2<x && x<10
b) pow(x+y,m+n+1)
c) (-b+sqrt(b*b-4*a*c))/(2*a)









Question 2: Arithmetic Operators (4 marks)

The following expressions evaluate to a boolean constant (true or false). What are they?

(a) true !=! true

Answer: true

(b) true || false && false

Answer: true

(c) 0 == 5 >= 6

Answer: true

(d) 8 * - 3 / 4 >= 11 * (5 - 2) % 3

Answer: false


Question 3: Arithmetic Operators (5 marks)

What is the output of the following C++ statements?

(a) cout << 2.5 + 8 / 3;

Answer: 4.5

(b) cout << double(11/4) + int(3.5 C 1);

Answer: 4

(c)
int x=1, y=2, z=3;
x += y *= z++;
cout << x << " " << y << " " << z << endl;

Answer: 7 6 4
(Because we did not cover multiple assignments in lecture, full marks for any written answer, but zero marks if no written answer)

Question 4: If statements (4 marks: 2 each)

(a) What is wrong with the following code? (Hint: it is a syntax error.)

int n;
cin >> n;
if(n > 0) cout << "profit";
else if(n==0)
cout << "break even";
else(n<0)
cout << "negative";

Answer: should be:
else
cout << "negative";

(b) What will the output be if the mark is 85?

if (mark>60)
cout<<"The grade is D"<<endl;
else if (mark >70)
cout<<"The grade is C"<<endl;
else if(mark>80)
cout<<"The grade is B"<<endl;
else if (mark>90)
cout<<"The grade is A"<<endl;
else
cout<<"The grade is F"<<endl;

Answer: The grade is D


Question 5: Dangling-else (2 marks)

What is the output of the following C++ statements?

int n, m, k, result;
n=10