You are on page 1of 33

Late Summer Examination Period 2022 — August — Semester B

ECS401U/A Procedural Programming Duration: 3.5 hours

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:

Below this line is for examiner use only.

Q1a +Q1b +Q1c =

Q2a +Q2b +Q2c =

TOTAL / 50 = TOTAL / 100 = 0

Examiners:
Prof. Paul Curzon, Dr Raymond Hu

© Queen Mary University of London, 2022


Page 2 ECS401U/A (2022)

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 above code contains 4 compile time errors that are

1 -> int i declaration missing


2-> i and ++ have a space in them
3-> "a[i] == key" are incomparable operands
4-> System.out.println(i) missing ';' in the end.

Run time 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.

The below on each page are for examiner use only.

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

The below on each page are for examiner use only.

Turn over
ECS401U/A (2022) Page 5

Write EXACTLY what is printed by the code here:

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

The below on each page are for examiner use only.

Turn over
Page 6 ECS401U/A (2022)

(ii) int[] myarr = new int[4]; // L1


for (int i = 0; i < myarr.length; i = i+2) { // L2
myarr[i] = i+1; // L3
myarr[i+1] = -(i+1); // L4
System.out.print(myarr[i] + " " + myarr[i+1]); // L5
}

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

The below on each page are for examiner use only.

Turn over
ECS401U/A (2022) Page 7

Write EXACTLY what is printed by the code here:

1 -13 -3

Explain in your own words what the code does step by step here:

It runs a loop upto array size that is four.


In first iteration it sets array [ 1, -1 ,0, 0] then prints "1 -1".
Then our i is incremented by 2, i =2 and it is less than 4 so we again have a iteration
In second iteration the array is set to [1, -1, 3, -3] it then prints "3 -3"

The below on each page are for examiner use only.

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

L4 1 "" true true

L5 1 "1" true

L7 2 "1" true

L3 2 "1" true

L4 2 "1" true false

L6 2 "1, 2" true

L7 4 "1, 2" true

L3 4 "1, 2" true

L4 4 "1, 2" true false

L6 4 "1, 2, 4" false

L7 8 "1, 2, 4" false

L3 8 "1, 2, 4" false

L8 8 "1, 2, 4" 1, 2, 4

The below on each page are for examiner use only.

Turn over
ECS401U/A (2022) Page 9

Write EXACTLY what is printed by the code here:

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.

The below on each page are for examiner use only.


[9 marks]

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!

Below is another example.


Secret word: .... (4 letters)
Guess one letter or the word: t
Sorry! Incorrect. 1/5 strike(s).
. . . (lines omitted)
Sorry! Incorrect. 4/5 strike(s).
Guess one letter or the word: perl
You lose! The word is: java

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:

• use at least one counter-controlled for-loop.


• be a procedural program. (Not an object-oriented program.)
• NOT use global variables. All variables should be declared as locally as possible.

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;

public class wordGuessing {

public static void main(String[] args) {

String word = "java";


String guessedWord = "....";
int numberOfStrike = 0;
String userInput = "";
Scanner scanner = new Scanner(System.in);
Boolean strike = true;

while (numberOfStrike != 5) {

System.out.print("Secret word: ");


for (int i = 0; i < guessedWord.length(); i++) {
System.out.print(guessedWord.charAt(i));
}

System.out.print("\nGuess one letter or the word: ");


userInput = scanner.nextLine();

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;
}

The below on each page are for examiner use only.

Turn over
ECS401U/A (2022) Page 13

scanner.close();
if (numberOfStrike == 5) {
System.out.println("You lose! The word is: " + word);
}

}
}

The below on each page are for examiner use only.

Turn over
Page 14 ECS401U/A (2022)

The below on each page are for examiner use only.

Turn over
ECS401U/A (2022) Page 15

The below on each page are for examiner use only.

Turn over
Page 16 ECS401U/A (2022)

The below on each page are for examiner use only.

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);

char[] initial_c = {’c’};


char[] initial_d = {’d’};
initial_d = initial_c;
initial_d[0] = ’D’;
System.out.println(initial_c[0] + " " + initial_d[0]);

[8 marks]
Type your answer in the box overleaf.

Turn over
Page 18 ECS401U/A (2022)

When we are copying array like this,

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.

But when we are copying values like this,

initial_b = initial_a;
initial_b = ’B’;

we are copying by value , so it won't change the other one.

The below on each page are for examiner use only.

Turn over
ECS401U/A (2022) Page 19

The below on each page are for examiner use only.

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:

{17, 15, 11, 13}


[7 marks]

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.

Bubble sort = n (n−1) / 2 = 4 ( 3) / 2 = 6


Merge sort = n - 1 = 4 - 1 = 3

The below on each page are for examiner use only.

Turn over
ECS401U/A (2022) Page 21

The below on each page are for examiner use only.

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;

public class Shop {


public static void printstart(){
System.out.println("Shopping list manager. Options:\n(1) Add item\n(2) List all in order of
entry\n(3) List total quantities by shop\n(4) Exit\n");
}
public static void main(String[] args) {
printstart();
int choice;
String itemname;
Scanner chinput = new Scanner(System.in);
Scanner itinput = new Scanner(System.in);
while(true){
System.out.println("\nEnter option [1-4]: ");
choice = chinput.nextInt();
if(choice == 1){
System.out.println("Item name? ");
}
}
}
}

The below on each page are for examiner use only.

Turn over
ECS401U/A (2022) Page 25

The below on each page are for examiner use only.

Turn over
Page 26 ECS401U/A (2022)

The below on each page are for examiner use only.

Turn over
ECS401U/A (2022) Page 27

The below on each page are for examiner use only.

Turn over
Page 28 ECS401U/A (2022)

The below on each page are for examiner use only.

Turn over
ECS401U/A (2022) Page 29

The below on each page are for examiner use only.

Turn over
Page 30 ECS401U/A (2022)

The below on each page are for examiner use only.

Turn over
ECS401U/A (2022) Page 31

The below on each page are for examiner use only.

Turn over
Page 32 ECS401U/A (2022)

The below on each page are for examiner use only.

Mark / 10
Turn over
ECS401U/A (2022) Page 33

End of questions

You might also like