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

Fall 2004, Lecture Section 1, 2, 3
Midterm Examination
Monday, October 18, 2004 7:30 C 9:30PM

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 and one empty page for question 9.b).


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

1
Operator Precedence
/4

2
C++ operators
/9

3
If, switch, nested if
/7

4
Loops
/11

5
Array searching & sorting
/12

6
Functions, pass-by-value
/11

7
Pass-by-reference
/6

8
Passing arrays to functions
/12

9
Local & global variables
/16

10
Recursion
/12

Total
/100
/100







Question 1 : Operator Precedence (4 marks)

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

#include <iostream>
using namespace std;

void main(void){
int a = 5, b = 3, c = 4, d = 6, e =1;
cout << a-b*c%(d-e) << endl;
}

Answer (2 marks):
3



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

#include <iostream>
using namespace std;

void main(void){
int a = 5, b = 3, c = 2, d = 2;
cout << ++a/3-c*d << endl;
}


Answer (2 marks):
-2

Question 2: C++ operators (9 marks)

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

#include <iostream>
using namespace std;

void main()
{
int b=6,c=5;
if(b++==7&&++c==5)
{
b*=c;
cout<<++b<<endl;
}
else
cout<<b--<<endl;
}

Answer (2 marks):
7

b) Consider the following code and answer the questions.

int a=3,b=4;
++a*=b++;
cout<<a<<endl;

<i> What is the output the above code? (2 marks)

Answer(2 marks):
16

<ii> What is the output if we replace the statement ++a*=b++ by statement ++a*=++b?(2 marks)

Answer(2 marks):
20

<iii> The elementary operations executed by a = b++ can be written as a=b; b=b+1;. Please write down the elementary operations executed by ++a*=++b in the correct order. You can only use three elementary operations: +, * and =. (3 marks)

Answer(3 marks, 1 each, order must be correct):

a=a+1; b=b+1; a=a*b;
or
b=b+1; a=a+1; a=a*b;

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

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

#include <iostream>
using namespace std;

void main()
{
int c =4, d=3;
if(c==1)if(d==2)c=5;else if(d==3) c=6;el