=========================preview======================
(COMP104)midterm00F_sol.pdf
Back to COMP104 Login to download
======================================================
Hong Kong University of Science and Technology
COMP104: Programming Fundamentals and Methodology
Fall 2000, Lecture Section 1, 2, 3, 4
Midterm Examination
Wed 25 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 15 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
/ 4
2
/ 8
3
/ 6
4
/ 6
5
/ 6
6
/ 6
7
/ 10
8
/ 6
9
/ 6
10
/ 6
11
/ 8
12
/ 8
13
/ 10
14
/ 10
Total
/ 100
Question 1: Operator Precedence (4 marks)
What is the value of n after each of the following C++ statements are executed?
a) int n = 4-3+23%8/4*4;
b) int n = 9-8.0+7%6/5.0*4.0;
Key: (4 marks: 2 marks for each number)
a) 5
b) 1 (only give 1 mark if they write 1.0)
Question 2: If and While (8 marks)
What is the value of n after each of the following C++ statements are executed?
a) int n = -3;
if(!n)
n = n + 2;
if(n)
n = -n;
n = n + 4;
b) int n=1, a=4, b=6, c=8;
if(a < 3 || b>5 && c<9)
n = n + 2;
c) int m=4, n=5, i=0, k=3;
if(m>=0) if(k<=10) if(i>0) n=2; else if(n<4) n=3;
else n=4; else n=6; else n=7;
d) int n = 2;
while ( n < 11 )
if(n%3)
n = n+2;
else
n = n+4;
e) bool n = 2+4*2==12||4>6==2>3&&!false;
Key: (8 marks)
a) 7 (1 mark)
b) 3 (1 mark)
c) 4 (2 marks)
d) 12 (2 marks)
e) true (or 1) (2 marks)
Question 3: Dangling Else (6 marks)
Consider the following selection statement using if-else:
1: int a=-3, b=4, c=4;
2: if(a>=0)
3: if(b>=0)
4: c = 3;
5: else
6: c = 2;
7:
(a)
What is the value of c at line 7?
(b)
Insert a pair of curly braces (i.e., {}) in the code below to indicate how C++ interprets this program.
1: int a=-3, b=4, c=4;
2: if(a>=0)
3: if(b>=0)
4: c = 3;
5: else
6: c = 2;
7:
(c)
Insert a pair of curly braces (i.e., {}) in the code below so that the value of c at line 7 will be equal to 2.
1: int a=-3, b=4, c=4;
2: if(a>=0)
3: if(b>=0)
4: c = 3;
5: else
6: c = 2;
7:
Key: (6 marks: 2 marks for each part)
(a) c=4 (2 marks)
(b) 1: int a=-3, b=4, c=4; (2 marks)
2: i