Computer Science 1 Ah

Similar documents
Computer Science 1 Ah

Pace University. Fundamental Concepts of CS121 1

Computer Science 1 Bh

Computer Science 1 Bh

CS 231 Data Structures and Algorithms, Fall 2016

Computer Science CS221 Test 2 Name. 1. Give a definition of the following terms, and include a brief example. a) Big Oh

Selected Questions from by Nageshwara Rao

COS 126 General Computer Science Spring Written Exam 1

CE221 Programming in C++ Part 1 Introduction

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

Lecture #6-7 Methods

COE318 Lecture Notes Week 4 (Sept 26, 2011)

Fall 2005 CS 11 Final exam Answers

ESC101 : Fundamental of Computing

DO NOT. UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N.

Full file at

CS171 Midterm Exam. October 29, Name:

Complexity, General. Standard approach: count the number of primitive operations executed.

double d0, d1, d2, d3; double * dp = new double[4]; double da[4];

Computer Science 1 Bh

CSE 143. Complexity Analysis. Program Efficiency. Constant Time Statements. Big Oh notation. Analyzing Loops. Constant Time Statements (2) CSE 143 1

PROGRAMMING FUNDAMENTALS

Java Bytecode (binary file)

CS111: PROGRAMMING LANGUAGE II

Getting started with Java

CS2 Practical 1 CS2A 22/09/2004

CSE 332 Autumn 2013: Midterm Exam (closed book, closed notes, no calculators)

Your data structure should implement all operations in logarithmic time (or better) as a function of the size of the queue.

Programming Language Concepts: Lecture 2

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

CS2141 Software Development using C/C++ C++ Basics

Short Notes of CS201

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

CSE373 Fall 2013, Midterm Examination October 18, 2013

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

Introduction to Programming Using Java (98-388)

FORM 2 (Please put your name and form # on the scantron!!!!)

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

CS201 - Introduction to Programming Glossary By

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

COS 226 Algorithms and Data Structures Fall Midterm

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

University of Palestine. Mid Exam Total Grade: 100

Final. Please write (printing clearly) the infonnation requested in the boxes at the top of this page.

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Recursion: Factorial (1) Recursion. Recursion: Principle. Recursion: Factorial (2) Recall the formal definition of calculating the n factorial:

Computer Science 1 Bh

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

public class Test { static int age; public static void main (String args []) { age = age + 1; System.out.println("The age is " + age); }

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Zheng-Liang Lu Java Programming 45 / 79

CS134 Spring 2005 Final Exam Mon. June. 20, 2005 Signature: Question # Out Of Marks Marker Total

protected BinaryNode root; } 02/17/04 Lecture 11 1

McGill University Faculty of Science School of Computer Science. MIDTERM EXAMINATION - Sample solutions. COMP-250: Introduction to Computer Science

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Data Structures in Java

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Intermediate Code Generation

Computer Science II (20082) Week 1: Review and Inheritance

Examination Questions Midterm 1

1 Shyam sir JAVA Notes

TeenCoder : Java Programming (ISBN )

Searching Algorithms/Time Analysis

CSCE 2014 Final Exam Spring Version A

UNIVERSITY OF WATERLOO DEPARTMENT OF ELECTRICAL AND COMPUTER ENGINEERING E&CE 250 ALGORITHMS AND DATA STRUCTURES

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Recursion. EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG

Introduction to Computing II (ITI 1121) Final Examination

Computer Science Foundation Exam

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Syntax Errors; Static Semantics

Midterm I Exam Principles of Imperative Computation Frank Pfenning, Tom Cortina, William Lovas. September 30, 2010

CMPT 125: Lecture 3 Data and Expressions

ECE 242 Fall 13 Exam I Profs. Wolf and Tessier

Lecture 3. Lecture

1007 Imperative Programming Part II

Fun facts about recursion

1.00/1.001 Introduction to Computers and Engineering Problem Solving. Final Exam

Operators and Expressions

CSI33 Data Structures

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Algorithm efficiency can be measured in terms of: Time Space Other resources such as processors, network packets, etc.

QUIZ 2 Introduction to Computer Science (COMP 250) Mon. March 2, 2009 Professor Michael Langer

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

About this exam review

CS260 Intro to Java & Android 03.Java Language Basics

Priority Queues and Binary Heaps. See Chapter 21 of the text, pages

UNIVERSITY REGULATIONS

Programming Language Concepts: Lecture 2

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

COE318 Lecture Notes Week 3 (Week of Sept 17, 2012)

Summer Final Exam Review Session August 5, 2009

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

CS 110 Practice Final Exam originally from Winter, Instructions: closed books, closed notes, open minds, 3 hour time limit.

CS 314 Exam 2 Fall 2017

CPSC 211, Sections : Data Structures and Implementations, Honors Final Exam May 4, 2001

CIS 110 Introduction to Computer Programming Summer 2014 Final. Name:

Transcription:

UNIVERSITY OF EDINBURGH course CS0077 COLLEGE OF SCIENCE AND ENGINEERING SCHOOL OF INFORMATICS Computer Science 1 Ah Resit Examination Specimen Solutions Date: Monday 1st September 2003 Time: 09:30 11:00 (one and a half hours) Place: Adam House Room: Ground Floor Board of examiners Chair: M. R. Jerrum External Examiner: R. Dyckhoff Notes about Specimen Solutions 1. These specimen solutions are issued for guidance only, to help as a revision aid. They do not represent a complete picture of how the exam was marked; they are specimen solutions, not a marking guide. 2. The solutions typically present one answer from a set of possible answers. Often, answers which have alternative wording or different technical details are equally acceptable. 3. If you have any questions concerning these solutions, please contact the course organiser. Please note that the course organiser will not be able to answer questions about the marking of the exam.

Question 1 (a) Fill in the type and value of each of the Java expressions which is printed out by the code fragment shown below. Assume that the statements are executed in order. [7 marks] String x = "Nunavut"; int b = 7; Type: Value: System.out.println(x + b); String "Nunavut7" System.out.println(x.length() + b); int 14 System.out.println(x.length() == b); boolean true double d = 2.4; System.out.println((int)d * (float)d); float 4.8 Object o1 = new Object(); Object o2 = new Object(); System.out.println(o1 == o2); boolean false o1 = null; o2 = null; System.out.println((o1 == o2)? y : n ); char y (b) Operators and methods in Java can be overloaded. Explain the meaning of this term, using one of the expressions above as an example. [3 marks] An overloaded operator or method is one which has the same name, but different underlying implementations for different types. An example from above is the use of the operator +. In the first System.out line, + stands for concatenation of strings; in the second output line, + stands for integer addition.

Question 2 (a) A company has been using a software inspection process to help ensure that their programs do not contain certain kinds of defect. The company wishes to switch from their previous programming language, which provided few built-in checks, to Java, which provides strong typing and other static analysis mechanisms during compilation. Using your knowledge of the Java language, say which of the following manual checks will still be necessary when code is compiled with the Java compiler javac, and which checks will no longer be needed. Place a tick in the box if the manual check is still necessary with Java, and a cross otherwise. [6 marks] Do arithmetic expressions have only numerically typed operands? Is every field of a new object initialized? Are any variables referenced before initialization? Is the upper bound of array accesses length-1 and not length? Is every method invocation on a non-null object? Do all method calls have the correct number of parameters? (b) The spiral model of the software production process considers software construction as an iterative process, revolving through four quadrants. Give a brief outline of the process and mention some of its advantages. [4 marks]

The spiral model looks like this: Planning Customer evaluation Risk analysis Engineering The process starts in the planning stage, and after each step of risk assessment it can be decided whether to proceed forward. Advantages of the model are that the iterative nature allows flexibility (the model is robust), and that it is visible, since it requires that each prototype is documented.

Question 3 A ternary tree is a like a binary tree, except that each node has up to three children in a given order: a left child, a middle child, and a right child. (a) In terms of n, how many leaves does a complete ternary tree of height n have? 3 n [1 mark] (b) Define a class TernaryTree for representing nodes of ternary trees in Java. As with the representation of binary trees in lectures, use the null object for empty trees, so that objects from your class can be used for nodes with one or more children missing. Each non-empty node should store a character item. No methods are required for this part of the question. [4 marks] class TernaryTree { char item; TernaryTree left; TernaryTree middle; TernaryTree right; (c) Write a static method lookup for your class that takes a character and a TernaryTree object as arguments and has TernaryTree result type. The method should treat the ternary tree argument as a binary search tree by ignoring the middle children of the nodes in the tree. If it finds the character argument at some node of the search tree, the middle child of that node should be returned. If the character argument is not found, null should be returned instead. Such a method could be used to treat a ternary tree as a trie. [5 marks] public static TernaryTree lookup(char a, TernaryTree t) { if (t == null) return null; if (a == t.item) return t.middle; if (a < t.item) return lookup(a, t.left); else return lookup (a, t.right);

Question 4 (a) Consider the following Java class definitions (Note: it is deliberate that there are no fields and that the methods do nothing!). class C1 { public void twiddle () { public void fiddle () { class C2 extends C1 { public void flip () { public void flop () { How many different methods can be invoked on an object of class C1? Ignore methods from the Object class that are available in every class. 2 [1 mark] How many different methods can be invoked on an object of class C2? Again ignore methods from the Object class. 4 [1 mark] (b) Consider the following Java fragment. C2 x = new C2(); C1 y = x; y.flip(); C1 z = new C1(); ((C2)z).flip(); // Line A // Line B i. The statement on line A will generate a compiler error. Describe and explain the error. [3 marks] The compiler will complain that the object referenced by y has no flip method. This is because y is declared to be a reference to a C1 object. The compiler is unable to determine that the object which y references at this point will actually be a C2. ii. Write a revised version of line A, which achieves the desired effect of invoking the flip method on the object referenced by y. You should not make explicit mention of x. ((C2) y).flip(); iii. The statement on line B has a problem too. Explain what this is and describe how it will become apparent to the programmer. [3 marks] The object referenced by z cannot be cast to C2 because it was constructed as a C1 object (and C1 is a superclass of C2). The compiler cannot detect this error. The JVM will throw a ClassCastException when the statement is executed.

Question 5 (a) Construct finite state machines with the input alphabet {0, 1 that: i. Accept exactly those strings in which every 0 is immediately followed by at least one 1. The empty string should be accepted.

1 0 A B 1

ii. Accept exactly those strings containing just 0s and 1s in which there are never two consecutive 1s. The empty string should be accepted. [3 marks]

0 1 A B 0 1 C 0,1

(b) Can a finite state machine accept exactly the following sets of strings? Write yes in the box if so and no otherwise. i. All strings of 0s and 1s containing exactly three more 0s than 1s. no [1 mark] ii. All strings of 0s and 1s containing at least three more 0s than 1s. no [1 mark] (c) Write a regular expression that describes all strings containing just 0s and 1s in which there are never two consecutive 1s (the same set as in part (a)(ii) above). [3 marks] (0 10) (0 10) 1

Question 6 (a) What operations take place when a Java method with parameters in invoked? Comment on the relationship between the formal and actual parameters at the end of the invocation. [3 marks] Firstly the actual parameter expressions are evaluated in left-to-right order to give the values that are to be passed to the method. The formal parameters are given these initial values and the method body executed. If the formal parameter variables are updated in the method body, this change is not reflected in the actual parameters that were used for this invocation.. (b) Consider the following Java program. class Params { static void printinner(string s) { s = s + "!"; System.out.println(s); static void printmiddle(string s) { s = s + "!"; System.out.println(s); printinner(s); System.out.println(s); static void printouter(string s) { System.out.println(s); printmiddle(s); System.out.println(s); public static void main(string[] args) { printouter("hello"); What output does the program produce? [5 marks] Hello Hello! Hello!! Hello! Hello (c) What does it mean for a Java method to be marked as static? Are there any consequences for what code can appear in the method s body? All arguments to a static method are passed explicitly as actual parameters: a static method is not invoked on an object as a dynamic method is. A consequence is that it is not appropriate in a static method body to use fieldnames or invoke methods that implicitly or explicitly refer to the this argument of dynamic methods.

Question 7 Recall the selection sort algorithm for sorting an array of n integers: for (int i = 0; i <= n - 2; i++) { // Comment A int smallest = i; for (int j = i + 1; j <= n - 1; j++) if (A[j] < A[smallest]) smallest = j; // Comment B int temp = A[smallest]; A[smallest] = A[i]; A[i] = temp; (a) Suggest text for Comment A that concisely explains the effect of executing lines 3 5. Looks for the smallest element among A[i] to A[n-1] and records its location in the variable smallest. (b) Suggest text for Comment B that concisely explains the effect of executing lines 7 9. [1 mark] Swaps the contents of array elements A[i] and A[smallest]. (c) Suppose n = 6 and the array A is initialised to 4 9 6 1 3 8 Sketch the contents of array A after each iteration of the for-loop over i. [5 marks] After iteration 1: 1 9 6 4 3 8 After iteration 2: 1 3 6 4 9 8 After iteration 3: 1 3 4 6 9 8 After iteration 4: 1 3 4 6 9 8 After iteration 5: 1 3 4 6 8 9 (d) What is the worst case run time (as a big-oh expression in terms of n) for sorting n elements using selection sort? O(n 2 )

Question 8 (a) For each of the following pairs of formulas give a truth-value assignment at which the formulas have different truth values. i. P Q and P Q P f, Q t or P t, Q f [1 mark] ii. P Q and Q P P f, Q t or P t, Q f [1 mark] iii. P Q and P Q Only P f, Q t [1 mark] (b) i. Using the algebraic laws of boolean logic and a chain of equivalences argument, simplify the logical expression (P Q) P. writing each step of the simplification on a separate line. (P Q) P ( P Q) P ( Q P ) P Q ( P P ) Q t t ii. Is this expression a tautology? Explain. [1 mark] Yes, because it is (equivalent to) true for all truth values of P and Q. (c) i. Write a boolean-valued Java expression that evaluates to true when a Java variable x of type int[] is an array of 2 equal integers, and evaluates to false for all other possible values of x. Your solution should contain at least one strict or conditional logical operator. x!= null && x.length = 2 && x[0] == x[1] ii. Does it matter whether the logical operator(s) you use in your solution are strict or conditional? Discuss. Both must be conditional. If the left-hand one is not, the evaluation of x.length raises an exception when x is null. If the right-hand one is not, the evaluation of one of the array index expressions will raise an exception when x is an array of length 0 or 1.

Question 9 (a) Consider the recursive method public static int f(int i) { int r; if (i == 0) r = 1; else if (i % 2 == 0) r = f(i - 2) + f(i - 1); else r = 2 * f(i - 1); System.out.print(r + " "); return r; 1 1 2 3 6 One approach is to read values off a call tree that has call edges annotated with return values. What is printed out if f(3) is evaluated? Show your working clearly. [4 marks] (b) In Java, each method invocation is associated with a distinct activation record. What kind of information is held in an activation record? Values of arguments and local variables. Position in method code to resume at after return of method call. (c) Complete the code below for a method calculator which should read down an input stack a of ints, interpreting each as either data or an instruction. A non-negative element should be interpreted as data and should be inserted on the top of the computation stack s. A negative element should be interpreted as an instruction to replace the top two integers on the stack with their sum. The method should return the top value on the computation stack when the input stack is empty. [4 marks] public static int calculator (intstack a) { intstack s; while (!a.isempty()) { if (a.top() >= 0) s.push(a.pop()); else s.push(s.pop() + s.pop()); return s.top(); For example, if the input stack holds values 1, 2, 1, 3, 1 top-to-bottom, calculator should return (1 + 2) + 3 = 6. Assume intstack supports the following standard stack methods: public boolean isempty() public int pop() public int top() public void push(int i) and assume sum instructions are only included in the input stack when they are sensible.

Question 10 (a) Consider the following implementation of a variable-length integer array class. public class intarraylist { // Represents the array a[0]... a[size - 1] private int[] a; private int size; // Always 0 <= size < a.length... i. Write a method addlast() which takes an int value as argument and adds it to the end of the intarraylist object it is invoked on, providing there is space in the internal array. The method should return a boolean value, true just when the add is successful. public boolean addlast(int i) { if (size >= a.length) return false; a[size++] = i; return true; ii. Describe how you could modify your implementation of addlast() so that it is successful even when the the internal array is initially full. [3 marks] If size < a.length, the method should add the argument value as before. If size == a.length, the method should first allocate a new array of say 2 times the current size of a, copy the contents of a to this new array, and use this new array to replace a. (b) Complete the method below for checking whether a given object is a member of a given collection. Assume objects can be compared using an equals() method. Hint: use an iterator. [3 marks] public boolean member(object o, Collection c) { boolean r = false; Iterator i = c.iterator(); while (i.hasnext()) { r = r o.equals(i.next()); return r;

(c) Compare the time efficiency of accessing an element in a LinkedList object at a position referred to by an iterator and by an integer index. Access by iterator is in constant time. An access by integer index has to work from one end of the linked list, so worst case it can take time proportional to the list length.