Professional Documents
Culture Documents
This a 2.5-hour online exam, which must be started within a 24-hour period. There is an
additional 1 hour to resolve any IT issues.
You MUST submit your answers within 3.5 hours of your exam start time.
All instructions and guidelines from the exam page should be followed.
This is an open-book exam and you may refer to lecture material, text books and online
resources. The usual referencing and plagiarism rules apply, and you must clearly cite any
reference used.
You must upload a copy of this booklet containing your answers as a SINGLE PDF file. Multiple
submissions are not permitted. All answers must be typed into the text fields of this booklet.
Calculators are permitted in this examination. Please state on your answer book the name and
type of machine used.
You may also compile and run code. Note, the focus on marking code is on whether the code
is logically correct, and the explanations of it, rather than on minor details of syntax that might
be picked up by a compiler.
Answer ALL questions
You MUST adhere to the word limits, where specified in the questions. Failure to do so
will lead to those answers not being marked.
YOU MUST COMPLETE THE EXAM ON YOUR OWN, WITHOUT CONSULTING OTHERS.
200934323
Please fill in your student number here:
Examiners:
Prof. Paul Curzon, Dr Raymond Hu
Question 1
(a) Compare and Contrast in your own words compile-time errors with run-time errors.
Illustrate your answer using the code below.
This code is intended to search an array of size 200 printing the location of all entries
that match the key.
Note you are NOT required to explain or trace this code, just use it to illustrate points
you make about errors.
public static void searchALL (String[]a, int key)
{
for (i = 0; i <= 200; i ++)
{
if(a[i] == key);
{
System.out.println(i)
return;
}
}
return;
}
[6 marks]
Type your answer in the box overleaf.
Turn over
ECS401U/A (2022) Page 3
Compile-Time Errors:
The Errors that occur due to incorrect syntax are known as compile-time errors or sometimes
also referred to as syntax errors.
The errors that causes the program to crash are called Run time errors like 1/0 or accessing a
null value.
The run time error in the above code is the loop iteration size that is set to fixed 200, not to array
size. So if we recieve an array of size 100 but we try to get the element at 101 it will make our
program crash due to index out of bound error.
Mark /6
Turn over
Page 4 ECS401U/A (2022)
(b) Complete the dry run table for each fragment of code given in the question subparts
that follow. Give the value(s) printed out when each is executed. Justify your answers
by explaining in your own words the execution of the code.
(i) int a = 5; // L1
int b = 12; // L2
int tmp = a; // L3
a = b; // L4
b = tmp; // L5
if (a < b) { // L6
System.out.print(a + " < " + b); // L7
} else {
System.out.print(a + " >= " + b); // L8
}
Complete the dry run table (you may not need all rows):
LINE a b tmp a < b Printed
L1 5
L2 5 12
L3 5 12 5
L4 12 12 5
L5 12 5 5
L6 12 5 5 false
L8 12 5 5 false 12 >= 5
Turn over
ECS401U/A (2022) Page 5
12 >= 5
Explain in your own words what the code does step by step here:
It first declares three variables with their values, a=5, b=12 and temp=5.
It then swap both of their values and then check whether a value is less than b or not.
If a is less than b then, 'a < b' is printed
Else 'b >= a' is printed
Turn over
Page 6 ECS401U/A (2022)
Complete the dry run table (you may not need all rows):
myarr
LINE [0] [1] [2] [3] i i < myarr.length Printed
L1 0 0 0 0
L2 0 0 0 0 0 true
L3 1 0 0 0 0 true
L4 1 -1 0 0 0 true
L5 1 -1 0 0 0 true 1 -1
L2 1 -1 0 0 2 true
L3 1 -1 3 0 2 true
L4 1 -1 3 -3 2 true
L5 1 -1 3 -3 2 true 3 -3
L2 1 -1 3 -3 4 false
Turn over
ECS401U/A (2022) Page 7
1 -13 -3
Explain in your own words what the code does step by step here:
Turn over
Page 8 ECS401U/A (2022)
(iii) int x = 1; // L1
String res = ""; // L2
while (res.length() < 7) { // L3
if (res.length() == 0) { // L4
res = res + x; // L5
} else {
res = res + ", " + x // L6
}
x = x * 2; // L7
}
System.out.println(res); // L8
Complete the dry run table (you may not need all rows):
LINE x res res.length()<7 res.length()==0 Printed
L1 1
L2 1 ""
L3 1 "" true
L5 1 "1" true
L7 2 "1" true
L3 2 "1" true
L8 8 "1, 2, 4" 1, 2, 4
Turn over
ECS401U/A (2022) Page 9
1, 2, 4
Explain in your own words what the code does step by step here:
It adds up the value of x to the res stirng up until the string size is less than 7, if it gets greater
than or equal to 7 it exists.
In the first iteration res is chagned to "1" then in the next iteration it is changed to "1, 2" and in
the last it is changed to "1, 2, 4" making its size equal to 7 and then our loop breaks and res is
printed.
Mark /9
Turn over
Page 10 ECS401U/A (2022)
(c) Write a FULL Java procedural program (not JHUB) for a simple word guessing
game. Below is an example of the required program behaviour. The bold text is user
keyboard input. The player is allowed to guess one letter or the whole word incorrectly
up to 5 times; each incorrect guess is called a “strike”.
Secret word: .... (4 letters)
Guess one letter or the word: t
Sorry! Incorrect. 1/5 strike(s).
Guess one letter or the word: j
Correct! Guessed so far: j...
Guess one letter or the word: v
Correct! Guessed so far: j.v.
Guess one letter or the word: jive
Sorry! Incorrect. 2/5 strike(s).
Guess one letter or the word: java
You win!
The program starts by displaying one full stop (’.’) for each character of the secret
word. You may assume the word is hardcoded into the game, is in lower case, and is
of length greater than one.
In each round of the game, the game first checks if the player has reached the
maxinum number of strikes; if so, the player loses and the game ends. If not, the
game prints an input prompt.
The player then guesses either one letter (by entering a single character) or the whole
word (by entering multiple characters). If a single letter is guessed correctly, meaning
the character occurs in the word, the game reveals the positions of those occurrences
in the word and proceeds to the next round. If the whole word is guessed correctly,
the player wins and the game ends. If either kind of guess is incorrect, the player
gains a strike and the game proceeds to the next round.
Your program must:
Turn over
ECS401U/A (2022) Page 11
To gain a pass mark, your program must include meaningful use of an if-statement
and a loop. For a high mark, your program must be functionally and clearly correct,
and make good use of methods that take arguments and/or return results. It should
have good style generally. For a very high mark, your program must be elegantly
written with outstanding style, including good method decomposition.
You may find the following useful.
• Given a String, the charAt method returns the character at the given index
(counted from 0). E.g., "foobar".charAt(3) returns ’b’.
• The following method substitutes a character at a given index in a string. You
may copy and use this code directly.
// Returns a string given by replacing the character at
// position i in s with c. E.g.,
// replaceChar("....", 0, ’j’) -> "j..."
public static String replaceChar(String s, int i, char c) {
if (i < 0 || i >= s.length()) {
System.out.println("Index out of bounds: " + i);
System.exit(1);
}
char[] cs = s.toCharArray();
cs[i] = c;
return new String(cs);
}
[10 marks]
Type your answer in the boxes overleaf.
Turn over
Page 12 ECS401U/A (2022)
import java.util.Scanner;
while (numberOfStrike != 5) {
if (userInput.length() > 1) {
if (userInput.equals(word)) {
System.out.println("You win!");
break;
} else {
System.out.println("You lose! The word is: " + word);
break;
}
} else {
for (int i = 0; i < word.length(); i++) {
if (userInput.charAt(0) == word.charAt(i)) {
String newName = guessedWord.substring(0, i) + word.charAt(i)
+ guessedWord.substring(i + 1, guessedWord.length());
guessedWord = newName;
strike = false;
break;
}
}
if (strike) {
numberOfStrike += 1;
System.out.println("Sorry! Incorrect. " + numberOfStrike + "/5 strike(s).");
} else {
System.out.println("Correct! Guessed so far: " + guessedWord);
strike = true;
}
}
if (userInput.equals(word)) {
System.out.println("You win!");
break;
}
Turn over
ECS401U/A (2022) Page 13
scanner.close();
if (numberOfStrike == 5) {
System.out.println("You lose! The word is: " + word);
}
}
}
Turn over
Page 14 ECS401U/A (2022)
Turn over
ECS401U/A (2022) Page 15
Turn over
Page 16 ECS401U/A (2022)
Mark / 10
Turn over
ECS401U/A (2022) Page 17
Question 2
(a) Explain in your own words how and why assigning to a variable that holds a charac-
ter behaves differently to assigning to an array of characters. Illustrate your answer
with the following code.
char initial_a = ’a’;
char initial_b = ’b’;
initial_b = initial_a;
initial_b = ’B’;
System.out.println(initial_a + " " + initial_b);
[8 marks]
Type your answer in the box overleaf.
Turn over
Page 18 ECS401U/A (2022)
initial_d = initial_c;
initial_d[0] = ’D’;
we are copying the reference of the array.So any changes in one of the array will effect the
other array.
initial_b = initial_a;
initial_b = ’B’;
Turn over
ECS401U/A (2022) Page 19
Mark /8
Turn over
Page 20 ECS401U/A (2022)
(b) Explain in your own words why even the more efficient versions of bubble sort are
considered to be slow algorithms. Illustrate your answer using the example data:
Because Bubble sort still has the sorting complexity more than the faster sorting algorithms like
merge sort, so even the best version uptil now is still considered slow because of those faster
avalaible algorithms.
So considering the above example, as given in our lecture the best version of bubble sort takes
n (n−1) / 2 comparisions for the sorting where n=4 then we have a value of 6,
but in the merge sort it takes only n-1 comparisions to do the sorting, where n = 4 then we have
a value of 3. Still merge sort is faster than the bubble sort and hence it proves it.
Turn over
ECS401U/A (2022) Page 21
Mark /7
Turn over
Page 22 ECS401U/A (2022)
(c) Write a FULL Java procedural program (not JHUB) for managing a shopping list.
Below is an example of the required program behaviour. Bold is user keyboard input.
Shopping list manager. Options:
(1) Add item
(2) List all in order of entry
(3) List total quantities by shop
(4) Exit
Enter option [1-4]: 1
Item name? apple
Quantity? 1
Shop? dailyapple
Essential? [y/n] n
Enter option [1-4]: 1
Item name? chocolate
Quantity? 12
Shop? chocstop
Essential? [y/n] y
Enter option [1-4]: 2
apple 1 dailyapple n
chocolate 12 chocstop y
Enter option [1-4]: 3
dailyapple 1
chocstop 12
Enter option [1-4]: 4
The program starts by printing the options menu. The options may be used multiple
times (except for 4) in any order.
Option (1) asks the user for the details as illustrated above and adds the new item to
the list. The item and shop names should be non-empty strings. The quantity should
be numerical. The list may contain separate entries with the same item name (i.e., it
is not necessary to coalesce such entries). You may assume the maximum length
of the list is 10. Your program should disregard with a warning any attempts to use
option (1) if the list is full.
Option (2) lists all the items and their details by their order of entry. Option (3) lists
the total number of items to be purchased at each shop summed up as one value.
Option (4) exits the program.
Your output is allowed to differ in whitespace to that shown above, but must otherwise
be structurally the same.
Your program must
• use at least one each of a for-loop, a while-loop, and an array.
• be a procedural program. (Not an object-oriented program.)
Turn over
ECS401U/A (2022) Page 23
• NOT use global variables. All variables should be defined locally in a method.
You should not assume that the user always enters valid inputs. However, you may
assume numerical values are always entered as numbers.
For a pass mark, your program must include meaningful use of an if-statement and
a loop. For a high mark, your program must be functionally and clearly correct, make
good use of arrays, records and methods that take arguments and/or return results,
and handle erroneous inputs. It must be designed and written in a good program-
ming style. For a very high mark, your program must also define and make good
use of at least one abstract data type, have outstanding style (including appropriate
comments) and elegantly handle erroneous inputs.
Write your answer in the boxes in the following pages. Do NOT cut and paste more
into an answer box than the number of lines that are visible as anything not visible on
the page will not be marked.
[10 marks]
Type your answer in the boxes on the following pages.
Turn over
Page 24 ECS401U/A (2022)
import java.util.Scanner;
Turn over
ECS401U/A (2022) Page 25
Turn over
Page 26 ECS401U/A (2022)
Turn over
ECS401U/A (2022) Page 27
Turn over
Page 28 ECS401U/A (2022)
Turn over
ECS401U/A (2022) Page 29
Turn over
Page 30 ECS401U/A (2022)
Turn over
ECS401U/A (2022) Page 31
Turn over
Page 32 ECS401U/A (2022)
Mark / 10
Turn over
ECS401U/A (2022) Page 33
End of questions