Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

The University of the South Pacific

Serving the Cook Islands, Fiji, Kiribati, Marshall Islands, Nauru, Niue, Samoa, Solomon Islands, Tokelau, Tonga, Tuvalu, and Vanuatu.

School of Computing, Information and


Mathematical Sciences

CS111: Introduction to Computing Science

FINAL EXAMINATION – SEMESTER 2, 2013

Time Allowed 3 hours plus 10 minutes reading

100 marks (50% of final grade)


INSTRUCTIONS

1. This exam has three sections:


a. Section A: 30 marks
b. Section B: 30 marks
c. Section C: 40 marks
2. Answer all questions in sections A, B and C. There are no choices.
3. Write your answers spaces provided in this booklet. You can ask for
more paper if required.
4. This exam paper has a cover page, one page with instructions and
answer sheet for section A + 19 pages of questions.
5. The number of questions (Section A+B+C) is 25.
6. You can use calculators.
7. This exam is worth 50% of your overall mark. The minimum exam
mark is 40/100.

1
Name: Student Number: Page 1

Answer Key for Exam A


Section A (3 points each)

1. Which statement about the C++ programming language is true?


(A) The C++ language was invented by Alan Turing to demonstrate the concept of a stored
program computer.
(B) The C++ is a high-level language, developed initially as an enhancement of the C programming
language.
(C) The C++ is the successor of the Java programming language, and extends it with object
oriented features.
(D) The C++ language is an assembler language that was developed as a simplified version of the
C−− machine language.

2. (A)

cout << "It is almost summer\nToo nice a day for an exam\nJust three more hours\n";

(B) (C)

cout << "It is almost summer"; cout << "It is almost summer"
cout << "Too nice a day for an exam"; << "Too nice a day for an exam"
cout << "Just three more hours"; << "Just three more hours" << endl;

Which of these code snippets has as output:


It is almost summer
Too nice a day for an exam
Just three more hours

(A) Snippet (A)


(B) Snippet (B)
(C) Snippet (C)
(D) All of the above
3. In what stage of software development will you discover and resolve syntactic errors?
(A) When you try to understand the problem.
(B) When you write the pseudo code.
(C) When you write and compile the code.
(D) When you run the code to test whether it produces the expected outcome.
Name: Student Number: Page 2

4. Consider the figure to the right. Given lengths


a and b, the area A of the shaded area can be
computed as follows: a

a2
A = b2 −
2
Suppose you want to compute the area for a =
1.0 m and b = 2.5 m. The result should be in m2 .
Which of these code snippets is syntactically cor-
rect and computes the area correctly: b

(A) (B)

int a = 1.0; double a = 1;


int b = 2.5; double b = 2.5;
int area = (b*b) - (a*a)/2; double area = b*b - a*a/2;
cout << "Area: " << area << " m^2\n"; cout << "Area: " << area << " m^2\n";

(C) (D)

float a = 1.0; long a = 1.0;


float b = 2.5; long b = 2.5;
float area = (pow(b,2) - pow(a,2))/2.0; long area = b^2 - (a^2)/2;
cout << "Area: " << area << " m^2\n"; cout << "Area: " << area << " m^2\n";

(A) Snippet (A)


(B) Snippet (B)
(C) Snippet (C)
(D) Snippet (D)
5. Consider the following snippet:

int num = -1;


do{
num = num + 2;
for(int i=0;i<num;i++){
cout << num << ",";
}
}
while(num > 0 && num < 3);
cout << endl;

What is its output?


(A) It will print nothing.
(B) 1,
(C) 1,3,
(D) 1,3,3,3,
Name: Student Number: Page 3

6. (A) (B)

void swap(int &num1, int &num2){ bool swap(int &num1, int &num2){
int tmp = num1; int *tmp = &num1;
num1 = num2; num1 = &num2;
num2 = tmp; return num2 = tmp;
} }

(C) (D)

void swap(int num1, int num2){ int swap(int num1, int num2){
tmp = num1; num1 = num2;
num1 = num2; num2 = num1;
num2 = tmp; return num1,num2;
} }

Which of these functions is syntactically correct and swaps the values of parameters num1 and
num2?
(A) Function (A)
(B) Function (B)
(C) Function (C)
(D) Function (D)
Name: Student Number: Page 4

7. Assume that traffic fines are computed according to the following table:

drunk sober
speed ≥ 50 $100 $50
speed < 50 $75 $0

Let drunk be a char and speed an int. Which of the following snippets computes the correct fine?
(A) (B)

if(drunk == ’y’){ if(drunk == ’y’ ){


cout << "The fine is $100!\n"; cout << "The fine is $100!\n";
} }
else if (drunk != ’y’){ else if(drunk ==’y’ && speed < 50){
cout << "The fine is $75!\n"; cout << "The fine is $75!\n";
} }
else if(speed >= 50){ else if(drunk != ’y’){
cout << "The fine is $50!\n"; cout << "The fine is $50!\n";
} }
else if(speed <50){ else if(drunk != ’y’ && speed < 50){
cout << "No fine!\n"; cout << "No fine!\n";
} }

(C) (D)

if(drunk == ’y’){ if(drunk==’y’){


if(speed >= 50){ if(speed >= 50){
cout << "The fine is $100!\n"; cout << "The fine is $100!\n";
} }
else{ else{
cout << "The fine is $75!\n"; cout << "No fine!\n";
} }
} }
else{ else if (speed < 50){
if(speed >= 50){ if(drunk != ’y’){
cout << "The fine is $50!\n"; cout << "The fine is $50!\n";
} }
else{ else{
cout << "No fine!\n"; cout << "The fine is $75!\n";
} }
} }

(A) Snippet (A)


(B) Snippet (B)
(C) Snippet (C)
(D) Snippet (D)
Name: Student Number: Page 5

8. What will the following code snippet print:

double a[2] = {4,5};


double* ptr = a;
a[1] = 3;
cout << "Result " << *(ptr+1);

(A) Result 3
(B) Result 4
(C) Result 5
(D) The address of array a
9. Consider the following program:

int main(){
const int SIZE = 6;
double list[SIZE] = {3,5,2,1,4};

for(int i = 1; i<=SIZE;i++){
cout << list[SIZE-i] << ",";
}
return 0;
}

What will this program print?


(A) 1,2,3,4,5,6,
(B) 3,5,2,1,4,
(C) 0,4,1,2,5,3,
(D) This program has array bounds error and will not compile.
Name: Student Number: Page 6

10. data.txt

12.3 11.4 23.6 24.2 9.6 10.0 8.4 14.4 21.5 18.9

process data.cpp

# include <iostream>
# include <fstream>
using namespace std;

int main(){

ofstream logfile;
logfile.open("data.log");
ifstream datafile;
datafile.open("data.txt");

double total = 0;
double dataitem;
int item = 0;

cout << "Processing item ";


while(datafile >> dataitem){
total = total + dataitem;
item++;
cout << item << " ";
}

logfile << "Processed " << item << " data items.\n";
logfile << "The sum of all items is " << total << ".\n";
logfile.close();
datafile.close();

return 0;
}

The program process data.cpp reads the file data.txt and writes to file data.log. What will it
print to standard output?

(A) Processing item 12.3 11.4 23.6 24.2 9.6 10.0 8.4 14.4 21.5 18.9
(B) Processing item 1 2 3 4 5 6 7 8 9 10
(C) Processed 10 data items.
The sum of all items is 154.3.
(D) Processed 10 data items.
The sum of all items is 154.3.
Press any key to continue . . .
Name: Student Number: Page 7

Section B (5 points each)

11. Students for an introductory maths course are using a math tutor to test their math skills. Some are
complaining that the program doesn’t work correctly, and send the following screen shot:

**************************************************
* CS111 Math tutor *
**************************************************

Which exercise do you want to do?


Type ’L’ for linear equation solving,’*’ for multiplication.
Any other key to quit. L

What is the solution for x in the following equation 8*x - 32 = 0 ? 3


Well done.

Which exercise do you want to do?


Type ’L’ for linear equation solving,’*’ for multiplication.
Any other key to quit. L

What is the solution for x in the following equation 9*x - 72 = 0 ? 8


Well done.

Which exercise do you want to do?


Type ’L’ for linear equation solving,’*’ for multiplication.
Any other key to quit. L

What is the solution for x in the following equation 2*x - 6 = 0 ? 3


Sorry. The answer should have been: 4

Which exercise do you want to do?


Type ’L’ for linear equation solving,’*’ for multiplication.
Any other key to quit. q

FINAL TALLY
You answered 1 of 1 multiplication questions correctly.
You answered 2 of 3 linear equation questions correctly.
You answered 3 of 4 questions correctly.

Answer the following two questions in the space provided below: (1) What is the problem with this
program; what are mistakes the program makes? (2) Are these problems syntax errors (also called
compile-time errors) or are they logic errors (also called run-time errors or semantic errors)? Explain.
(1) The program sometimes marks a correct answer as wrong (3 is the solution to 2 x − 6 = 0),
and a wrong answer as correct (3 is not the correct solution to 8 x − 32 = 0). Also it counted
correct answers for multiplication questions, but there was no multiplication question. (2) This
problem is a semantic error. The program compiles fine, but when you run the program it turns
out that it does not compute what it is supposed to compute. Marking: 2 points if one problem
was correctly identified. 3 points if more than one was correctly identified. 1 mark if it correctly
says that it is a logic error. 1 mark is the explanation is correct.
Name: Student Number: Page 8

12. Consider the following code snippet:

double temp[6] = {23.0, 34.6, -1.2, 45.8, 104.3, 65.1} ;


cout << setprecision(1) << fixed;
for(int i =0; i<6;i++){
if(/*condition*/){
cout << setw(5) << temp[i];
}
else {
cout << setw(5) << " --- ";
}
}

Give a boolean expression to replace /*condition*/ , such the program prints the values in array temp
(temperature), but strikes out any value that is below 0 or above 100. If the latter is the case it will
just print - - - .
Please provide the expression in the space below:
temp[i]>=0 && temp[i]<=100 or !(temp[i]<0 || temp[i]>100)
Marking: 4 marks if correct except for the negation.

13. Consider the following code snippet:

1 int result = 1;
2 int factor = 1;
do{
3 factor++;
4 result = result * factor;
5 }while(result<=10);

6 cout << "The result is " << result << endl;


7 system("pause");
8 return 0;

The numbers on the left are line numbers.


Please provide the next 5 lines of the hand trace in the space below:
line result factor comment
1 1 initialising result to 1
2 ” 1 initialising factor to 1
3 ” 2 increment factor
4 2 ” 1 ∗ 2 is 2
5 ” ” Condition is true
3 ” 3 increment factor
4 6 ” 2 ∗ 3 is 6
5 ” ” Condition is true
Name: Student Number: Page 9

14. Consider the following program:

1 int score_mult = 0;
2 int score_div = 0;
3 double average, counter=0;
4 int* score = NULL;
5 int a=0, b=0, answer=0, expected=0;
6 char reply;
7
8 while(reply ==’*’ || reply == ’/’){
9 counter ++;
10 a = rand()%10 + 1;
11 b = rand()%10 +1;
12 if(reply == ’*’){
13 cout << "What is " << a << " multiplied by " << b << ": ";
14 expected = a * b;
15 //remember which of the scores to use
16 score = &score_mult;
17 }
18 else{
19 cout << "What is " << a << " divided by " << b << ": ";
20 expected = a / b;
21 //remember which of the scores to use
22 score = &score_div;
23 }
24 cin >> answer;
25
26 if(answer==expected){
27 cout << "Well done\n";
28 //increment the value of where pointer ’score’ points to by one
29 score = score + 1;
30 }
31 else{
32 cout << "The answer should have been " << expected << endl;
33 }
34 cout << "\nEnter ’*’ for multiplication, ’/’ for division, ’x’ to quit.";
35 cin >> reply;
36 }
37 average = (score_mult + score_div)/counter;
38 cout << "Your average is " << average << endl;

The numbers on the left are line numbers.


This program compiles and runs, but this program has still three common errors:
(a) Possible use of an uninitialized variable.
(b) Possible division by zero.
(c) Confusing pointers with the data they point to.

Each of these errors occurs exactly once. Describe where in the program each of these errors occurs,
which variables are involved, and what the effect of the errors on the output for the cost is.
Name: Student Number: Page 10

Answer question 14 here

(a) The first error occurs in line 8. Variable reply has no value. [1 point] (b) A possible division
by zero occurs in line 37. Variable counter was initialized to zero, and is used here. The while
loop could never be executed, and if that is the case, then a division by zero will occur. [1
point] (c) This error occurs in line 29. Pointer score is incremented, while the value should be
incremented. The correct version would be *score =*score+1; [1 point] The effect of the first
error will be that it is very likely that the loop will never execute. [1 point] The second error
means sometimes the result for the average can be a nonsense result. [1 point] The problem with
the confused pointer is that the score will not be kept. [1 point] (Maximal 5 points).
Name: Student Number: Page 11

15. Consider the following program:

1 int main(){
2 //This program prints the weekly schedule as a table.
3
4 const int SHIFTS = 3;//Number of shifts per day
5 const int DAYS = 5; //Number of working days
6 int bs[SHIFTS][DAYS] = {{2,4,2,3,1},{3,2,4,1,2},{1,0,2,1,1}};
7 int number = 0;
8
9 cout << "The schedule for this week\n\n";
10
11 cout << "\t";
12 for(int i = 0; i< DAYS; i++){
13 cout << "\tDay " <<i+1;
14 }
15 cout << endl;
16
17 //This is a nested for-loop
18 for(int i = 0; i< SHIFTS;i++){
19 cout << "Shift " << i+1 << "\t";
20 for(int j = 0; j< DAYS;j++)
21 cout << "\t" << bs[i][j]*12;
22 cout <<endl;
23 }
24 cout << endl;
25
26 system("pause");
27 return 0;
28 }

The numbers on the left are line numbers.


This program compiles and the executable runs and computes the fine correctly. However, there are
five problems with programming style.

(a) Use of magic constants.


(b) Poor comment
(c) Cryptic variable name.
(d) Unused variable.
(e) Poor use of brackets.
Each of these errors occurs exactly once. Describe exactly where each of these problems occurs, and
explain the issue.
Name: Student Number: Page 12

Answer question 15 here

(a) A magic constants is used in line 21. The meaning of the factor ’12’ is unclear. (b) The line
17 is a poor comment. It doesn’t say anything about the purpose of the loop. (c) Variable bs in
line 6 is a cryptic name. It should be changed to a meaningful name like schedule. Variable i
and j are common names for counters, and thus not cryptic. (d) Variable number in line 7 isn’t
used at all. (e) The inner for-loop in line 20 and 21 should use brackets. It seems like line 22 is
intended to be part of the loop, but that is not the case. [1 point each]
Name: Student Number: Page 13

16. Consider to the following reference report for the position of junior developer.

I’m happy to act as reference for Mr. John Doe. As I understand he applied
for a position as junior developer at your company. I hope that the information
in this email will be confidential, as it is very critical of Mr Doe. The problem
is not a lack of technical skills - he is actually very talented - but his conduct
as a programmer.

A main concern is his conduct as a team member. John seemed to take a de-
light to write code that is intentionally difficult to understand, just to
impress or frustrate the person who was assigned to review his code. Colleagues
have also reported that he replaced their name in the comment section by his
own, and thus effectively took credit for their work. When he was
warned to stop this behavior, he deliberately introduced a bug in a al-
most completed product out of spite. It took us two days identify and correct
this bug, and it delayed the release of our product. This was the very reason
why we asked him to leave our company.

A recent review of his work revealed that he reused copyrighted code with-
out informing us or the license holder. We had to redo the work to avoid the
risk of legal challenges. Furthermore, we were told by a competitor that Joe
shared confidential knowledge about our product with one of their de-
velopers who knew John since high school. This competitor warned us with an
assurance that they would of course not use the leaked information.

Joe might be technically brilliant, but he is anything but a responsible program-


mer. If you have any further question, please feel free to contact me.
Please fill in the blanks. Use 5 words or phrases from the following list:
Alan Turing, assembler code, ate fast food, Bjarne Stroustrup, Brian Kernighan, code of
conduct, coding guideline, competently advised, completed on time, deliberately introduced,
Dennis Ritchie, drank coffee, drove fast, got lunch, high-level code, intentionally difficult,
logical error, machine code, object oriented, professionally developed, reused copyrighted code,
shared confidential knowledge, slept in, solved brilliantly, syntax error, took credit, understood
the problem.
Name: Student Number: Page 14

Section C (A total of 40 points.)


This section asks you to develop a program asks a user to enter rainfall data and prints a histogram illustrating
the rainfall pattern. The user has to enter for each month of the year the number of rainy days, and the
program will print for each month a bar made up by the symbol ’*’, one star for each rainy day. The output
of the program might look like this:

Please enter the number of rainy days in month 1:1


Please enter the number of rainy days in month 2:2
Please enter the number of rainy days in month 3:4
Please enter the number of rainy days in month 4:8
Please enter the number of rainy days in month 5:11
Please enter the number of rainy days in month 6:12
Please enter the number of rainy days in month 7:9
Please enter the number of rainy days in month 8:7
Please enter the number of rainy days in month 9:5
Please enter the number of rainy days in month 10:3
Please enter the number of rainy days in month 11:2
Please enter the number of rainy days in month 12:0

Rainy day histogram:

*
* *
* *
* * *
* * * *
* * * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * * *
1 2 3 4 5 6 7 8 9 10 11 12

Press any key to continue . . .


Name: Student Number: Page 15

The program has to include two functions, plus the main function. The first function readdays(int
month) should read for month month the number of rainy days. It should validate that the number is
between 0 and 31. Its output/input might look like this:

Please enter the number of rainy days in month 3:42


Please enter a number between 0 and 31: 24

The second function void printrow(int data[],int length,int cutoff) will print one line of the
histogram. It should go through the elements of array data, from 0 to length, excluding length, and print
" * " if the value is larger than or equal to cutoff, and " " otherwise. Its output might look like this:

* * * * *

The main function should use these functions to create the histogram according to the following speci-
fication:
It should first read the number of rainy days for all 12 months, then print one line of the histogram
for 31, 30, . . . , 0 rainy days, and finally print in one line the numbers 1 to 12.

17. (4 marks) Which variables and constants do you need for the main function of this program, and what
are their types?
You need at least one variable, an array rainfall of size 12. The type of the array should be
12. In addition you need a counter i to count the number of days and months. Additionally
there could be constants const in DAYS=31 and const int MONTHS=12. Marking: 1 points for
identifying the main variables and constants, 1 if no unnecessary constant or variables, 1 point
for a proper name, and 1 points for the correct type.

18. (1 mark) Which type of loop is most suitable to validate that the number of rainy days entered is
between 0 and 31?
While-loop or do-loop

19. (1 mark) Which type of loop is most suitable to read in the number of rainy days for 12 months?
for-loop

20. (1 mark) Which type of loop is most suitable to print one line of the histogram for 31, 30, . . . , 0 rainy
days?
for-loop

21. (1 mark) Which type of loop is most suitable to print in one line for each of the 12 months either " "
or " * ", depending on whether the number of rainy days is below the cutoff or not?
for-loop
Name: Student Number: Page 16

22. (6 marks) Write a design for the main function in pseudo-code. Your solution should consider the
specification in the last paragraph of the introduction, and the fact that some steps should be per-
formed by the functions printrow and readdays.

For month 1 to 12
Read the number of rainy days
For day 31 to 0
Print one line of the histogram
For month 1 to 12
Print the number of the month

Marking: 1 point if it is proper pseudo-code. 2 points if it uses the correct type of loop. 2 points
if it is correct. 1 point if it has the right level of detail.
Name: Student Number: Page 17

23. (10 marks) Write C++ code for two functions. First, provide readdays(int month), which should
read for month month the number of rainy days and validate that the number is between 0 and 31.
Please provide the function in the space below:

int readdays(int month){


int days;
cout << "Please enter the number of rainy days in month " << month+1 << ":";
cin >> days;
while(days<0 || days>DAYS){
cout << "Please enter a number between 0 and 31: ";
cin >> days;
}
return days;
}

Marking: 1 point if the parameter definition and use of return is correct. 2 points if it correctly
validates the input. 1 point if it correctly reads the input. 1 point if there are no other serious
syntax errors.

Second, write function void printrow(int data[],int length,int cutoff). It should go through
the elements of array data, from 0 to length, excluding length, and print " * " if the value is larger
than or equal to cutoff, and " " otherwise. Please provide the function in the space below:

void printrow(int data[],int length,int cutoff){


cout << " ";
for(int i = 0;i<length;i++){
if(data[i]>=cutoff){
cout << " * ";
}
else {
cout << " ";
}
}
cout << endl;
}

Marking: 1 point if the parameter definition and use of return is correct. 2 points if it correctly
uses the array. 1 point if it correctly uses an if condition. 1 point if there are no other serious
syntax errors.
Name: Student Number: Page 18

24. (10 marks) Write a the main function int main(). Take into consideration your pseudo-code, and use,
if possible, the functions readdays and printrow.

int main(){

int rainfall[MONTHS] ={0};

for(int i = 0; i<MONTHS;i++){
rainfall[i] =readdays(i);
}
cout << endl;

cout << "Rainy day histogram:\n";


for(int i=DAYS; i>0;i--){
printrow(rainfall,MONTHS,i);
}

for(int i = 0; i<MONTHS;i++){
cout << setw(3) << i+1 ;
}
cout << endl << endl;

system("pause");
return 0;
}

Note: The exact formatting of the output isn’t essential.


Marking: 3 points if uses function correctly in the scope of the problem. 2 points if it uses array
correctly in the scope of the problems. 2 points if it uses loops correctly in the scope of the
problem. 3 points for correctness and structure. ”In the scope of the problem” means that no
points are given if the code is just a copy of some code with no relation to the problem.
Deductions for poor programming style, for incorrect syntax, for semantic mistakes, such as
incorrect use of loops, functions, decisions, conditions, etc.
Name: Student Number: Page 19

25. (6 marks) Present two test cases, i.e. specify input, and describe briefly the excepted output. For each
test case describe why you select that input for a test case.
Please provide the first test input with an explanation:
The first test is to enter 12 times the number 12. The program should print 12 bars each contains
12 stars. This test case tests the normal behavior of the program. Marking: 1 point if the input
is correctly chosen, 1 point if the output is correctly described, and one point if the motivation
for the test case makes sense.

Please provide the second test case with an explanation:


The second test case is to enter values larger than 31 or smaller than 0. The expected behavior is
that the program should ask to re-enter the data. This is to test what happens for unusual input.
Marking: 1 point if the input is correctly chosen, 1 point if the output is correctly described, and
one point if the motivation for the test case makes sense.

You might also like