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

Fall 2005, Lecture Section 1, 2, 3
Midterm Examination
Wednesday, October 12, 2005 7:00 C 9:00PM

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 17 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
Topic
Score

1
Operator Precedence
/4

2
C++ operators
/9

3
If, switch, nested if
/9

4
Loops
/15

5
Arrays
/10

6
Array searching and sorting
/7

7
Functions, pass-by-value
/10

8
Pass-by-reference
/10

9
Passing arrays to functions
/12

10
Local and global variables
/6

11
Recursion
/8

Total

/100




Question 1 : Operator Precedence (4 marks)

a) What is the value of variable n after executing the following C++ statements? (2 marks)

int n;
n = 8+3.5*(int)4.5/1.5;

Answer (2 marks): 17

b) What is the value of variable n after executing the following C++ statements? (2 marks)

int a = 5, b = 2, c = 7;
int n;
n = a/b*(c%2 + 4.5);

Answer (2 marks): 11

Question 2: C++ operators (9 marks)

a) What is the value of variable n after following C++ statements? (2 marks)

int n = 5, a = 4, b = 0, c = 8;
if (b<=6 && c>4 || a++==6)
n ++;
if (a!=4 || b>5 || c<=9)
n += a++;
if (c<=2 || a>=5 && b--==0)
n *= a++;

Answer (2 marks): 50

b) What is the value of variable n after following C++ statements? (2 marks)

int n = 5, a = -1, b = 3;
switch((--n)%4){
case 0: n++;
break;
case 1: n *= a++;
case 2: n +=--b;
case 3: --n;
default:n++;
}

Answer (2 marks): 5
c) Write a program to get three numbers from users, for integer variables a, b and c. If a is not zero, find out whether a is the common divisor of b and c.
(5 marks)

// Write your code here

Answer (5 marks)
# include <iostream>
using namespace std;
void main()
{
int a,b,c;
cin>>a>>b>>c; (1 mark)
if(a==0){ (1 mark)
cout<<"divisor can not be 0"<<endl;
}
else{
if(b%a==0&&c%a==0) (2 marks)
cout<<a<<" is a common divisor of "<<b<<" and "<<c<<endl;
else (1 mark)
cout<<a<<" is not a common divisor of "<<b<<" and "<<c<<endl;
}
}

Question 3: if, switch, nested if (9 marks)

a) Rewrite the following lines of code using a switch statement (and with no if statement). Assume a students score is a non-negative integer from 0 to 100. (4 marks)

int score;
cout << "Enter score:" << endl;
cin >> score;

if(score >= 90)
cout <