CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

Similar documents
CSC 1051 Algorithms and Data Structures I. Final Examination December 17, Name:

CSC 1051 Algorithms and Data Structures I. Final Examination December 18, Name:

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name:

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name: KEY. Question Value Score

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name: Question Value Score

CSC 1051 Algorithms and Data Structures I. Final Examination December 20, Name: KEY. Question Value Score

Happy Cinco de Mayo!!!!

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

Happy Cinco de Mayo!!!!

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 9, Name: KEY

// constructor: takes a String as parameter and creates a public Cat (String x) { name = x; age = 0; lives = 9; // cats start out with 9 lives }

Assignment 1 due Monday at 11:59pm

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

CSC Algorithms and Data Structures I. Midterm Examination February 25, Name:

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 26, Name: Key

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

Where do objects come from? Good question!

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

COE 212 Engineering Programming. Welcome to Exam II Thursday April 21, Instructors: Dr. Salim Haddad Dr. Joe Tekli Dr. Wissam F.

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 11, Name: KEY

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Recitation: Loop Jul 7, 2008

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 6, Name:

Selection Statements and operators

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 2, Name:

Module Contact: Dr Gavin Cawley, CMP Copyright of the University of East Anglia Version 1

Introduction to the Java Basics: Control Flow Statements

Designing Classes part 2

Chapter 4: Writing Classes

Selection and Repetition Revisited

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Encapsulation. Administrative Stuff. September 12, Writing Classes. Quick review of last lecture. Classes. Classes and Objects

Java I/O and Control Structures

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 1, Name: KEY A

Anatomy of a Class Encapsulation Anatomy of a Method

Operations. I Forgot 9/4/2016 COMPUTER SCIENCE DEPARTMENT PICNIC. If you forgot your IClicker, or your batteries fail during the exam

CS1083 Week 2: Arrays, ArrayList

Chapter. We've been using predefined classes. Now we will learn to write our own classes to define objects

H212 Introduction to Software Systems Honors

Java I/O and Control Structures Algorithms in everyday life

Designing Classes. Where do objects come from? Where do objects come from? Example: Account datatype. Dr. Papalaskari 1

COE 212 Engineering Programming. Welcome to Exam II Tuesday November 28, 2018

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

University of Massachusetts Amherst, Electrical and Computer Engineering

Question: Total Points: Score:

CPSC 219 Extra review and solutions

Chapter 3. Selections

University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ Test 2. Question Max Mark Internal External

Practice Midterm 1 Answer Key

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

if (x == 0); System.out.println( x=0 ); if (x = 0) System.out.println( x=0 );

Selection Statements and operators

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

Data Structures. Data structures. Data structures. What is a data structure? Simple answer: a collection of data equipped with some operations.

Section 002 Spring CS 170 Exam 1. Name (print): Instructions:

COE 211/COE 212 Computer/Engineering Programming. Welcome to Exam II Thursday December 20, 2012

Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) Midterm Examination

McGill University School of Computer Science COMP-202A Introduction to Computing 1

AP COMPUTER SCIENCE A

CSE 1223: Exam II Autumn 2016

Loops. CSE 114, Computer Science 1 Stony Brook University

COE 212 Engineering Programming. Welcome to Exam II Monday May 13, 2013

Selection and Repetition Revisited

Problem Grade Total

1 Short Answer (10 Points Each)

Selection and Repetition

CS 101 Fall 2006 Midterm 3 Name: ID:

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Advanced Java Concept Unit 1. Mostly Review

CSEN202: Introduction to Computer Science Spring Semester 2017 Midterm Exam

CS 101 Exam 2 Spring Id Name

AP CS Unit 3: Control Structures Notes

Instance Method Development Demo

Controls Structure for Repetition

Last Class. While loops Infinite loops Loop counters Iterations

CSCI 1226 Sample Midterm Exam

Name: Checked: Preparation: Investment Calculator with input and output to text files Submit through Blackboard by 8:00am the morning of Lab.

The Irving K. Barber School of Arts and Sciences COSC 111 Final Exam Winter Term II Instructor: Dr. Bowen Hui. Tuesday, April 19, 2016

CMP 326 Midterm Fall 2015

Principles of Computer Science I

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

WES-CS GROUP MEETING #9

CS 455 Midterm Exam 1 Fall 2016 [Bono] Thursday, Sept. 29, 2016

Decisions: Logic Java Programming 2 Lesson 7

CS212 Midterm. 1. Read the following code fragments and answer the questions.

Name: Checked: Preparation: Write the output of DeckOfCards.java to a text file Submit through Blackboard by 8:00am the morning of Lab.

Lab Exercise 1. Objectives: Part 1. Introduction

COE 212 Engineering Programming. Welcome to Exam II Friday November 27, 2015

Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

Name:... ID:... class A { public A() { System.out.println( "The default constructor of A is invoked"); } }

This exam is open book. Each question is worth 3 points.

Algorithms and Conditionals

Practice Problems: Instance methods

CSCI 1226 A Test #1. Wednesday, 10 October, 2018 Name: Student #: General Instructions Read and follow all directions carefully.

Transcription:

CSC 1051 Algorithms and Data Structures I Final Examination May 2, 2015 Name: Question Value 1 10 Score 2 10 3 10 4 10 5 10 6 10 7 10 8 10 9 20 TOTAL 100 Please answer questions in the spaces provided. If you make a mistake or for some other reason need more space, please use the back of and clearly indicate where the answer can be found. Good luck and best wishes for a wonderful summer!

1. ( / 10) What gets printed? Please show output as it will appear, or indicate NO OUTPUT, or show some of the output followed by INFINITE LOOP. int a = 5; Output: do a--; System.out.println(a); while (a >= 6) System.out.println("Done: " + a); Output: for (int a = 4; a > 0; a++) System.out.println(a * 2); System.out.println("Done: " + a); String[] notes = "do", "re", "mi"; for (String st: notes) System.out.println(st + st); Output: System.out.println("Done: "); for(int a = 1; a <= 3; a++) for (int b = 5; b <= 6; b++) System.out.println(a + "\t" + b); Output: System.out.println("Done");

2. ( / 10) a) Show what gets printed and rewrite using if/else: char ch = 'n'; System.out.print ("The answer is "); switch(ch) case 'y': System.out.println ("positive."); break; case 'N': System.out.println ("negative."); break; default: System.out.println ("unclear."); Output: Using if/else: 2. Show what gets printed and rewrite using while and if/else (i.e., eliminate the for and conditional operator): for (int a = 0; a < 4; a++) System.out.println(a + (a % 2 == 0? " yes": " no ")); Using while and if/else: Output:

3. ( / 10) Consider the following program: import java.util.scanner; import java.io.*; public class FinalS15FileIO public static void main(string[] args) throws IOException Scanner infile; PrintWriter outfile; infile = new Scanner (new File("data-in.txt")); outfile = new PrintWriter("data-out.txt"); while (infile.hasnext()) String line = infile.nextline(); Scanner scan = new Scanner(line); int count = 0; while (scan.hasnext()) String token = scan.next(); count ++; outfile.println(count); outfile.close(); a) Suppose the file data-in.txt is used as the input file. Show the contents of the file data-out.txt after execution of the program. b) List two examples of situations that could cause IOExceptions in the above code. c) Suppose you want to catch and handle the IOExceptions using the following catch clause: catch (IOException e) System.out.println("Warning: problem with IO. Run interactively."); infile = new Scanner(System.in); outfile = new PrintWriter(System.out); (i.e., keep running, but issue a warning and do interactive I/O instead) Show how to incorporate this in the above program: 1) Draw a box around the statements of the above program that you would include in the try block, and 2) mark the position where you would insert the catch code.

4. ( / 10) (a) Write a Java method findmax() with one parameter that is a 2D array of double, that finds and returns the largest of all the values in the 2D array. Assume that all the values will be positive. There may be repetitions, but it should not matter, the method should still return a value that is no less than any of the other values. The method should have one parameter (the 2D array of double) and it should return a double, and not print anything. (b) Assume findmax() is defined as a static method in the class below. Complete the code of main() below to use findmax so as to print the largest of the numbers stored in either of the arrays a and b (i.e., the largest number overall). public class ThisIsATest public static void main(string[] args) double[][] a =... (arrays are initialized with some values) double[][] b =... //**** print the largest value stored in either a or b

5. ( / 10). (a) Show the output produced by the following code fragment: String mess = ""; char[] grades = 'A', 'B', 'C', 'D', F'; for (char ch: grades) mess = ch + mess; System.out.println (mess); (b) Show the output produced by the following code fragment: char[] grades = 'A', 'B', 'C', 'D', F'; for (char ch: grades) System.out.print ((char) (ch + 1)); (c) Suppose an int array ratings contains values in the range 0-3. Write a code fragment that creates an array count that contains the frequency of occurrences of 0 s, 1 s, 2 s and 3 s in the ratings array, and then prints this information. Example: if the array ratings has these contents: ratings 0 1 2 3 4 5 6 2 3 2 1 0 2 2 Your code should create the array count with the following contents: count 0 1 2 3 1 1 4 1 and the output would be: Count for 0: 1 Count for 1: 1 Count for 2: 4 Count for 3: 1 Write your code fragment below. Assume the array ratings is already initialized to some values. Your code should work for any size array.

6. ( / 10) Suppose you have a Die class defined as follows: import java.awt.*; public class Die private int facevalue; // current value showing on the die // Constructor: Sets the initial face value. public Die() facevalue = 1; // Rolls the die and returns the result. public int roll() facevalue = (int)(math.random() * 6) + 1; return facevalue; ç Write your answer on facing page (back of previous page). ç // Face value mutator. public void setfacevalue (int value) facevalue = value; // Face value accessor. public int getfacevalue() return facevalue; // Returns a string representation of this die. public String tostring() String result = Integer.toString(faceValue); return result; // Draws the die on page at position x, y. public void draw (Graphics page, int x, int y) page.setcolor (Color.white); page.fillrect (x, y, 30, 30); page.setcolor (Color.black); page.drawstring(integer.tostring(facevalue), x+10, y+20); On the facing page, write the Java code for a driver class that uses the Die class to determine how likely it is to roll snake eyes, i.e., two ones. Use the following approach: Ø Declare and instantiate two Die objects, die1 and die2 Ø Roll them 10,000 times (or some sufficiently large number, specified by a constant in your program) while keeping track of how many times you rolled ones on both dice Ø In the end, print how many times the dice were rolled, the number of snake eyes, and proportion of snake eyes (i.e., probability). Careful: use a cast when dividing integers!

7. ( / 10) Suppose you have a Passenger class defined as follows to represent passengers in the Titanic: public class Passenger // instance data private int status; private boolean child; private char sex; private boolean survivor; // constructor public Passenger(int status, boolean child, char sex, boolean survivor) this.status = status; this.child = child; this.sex = sex; this.survivor = survivor; // tostring() returns String description of Passenger public String tostring() String pass = ""; switch (status) case 1: pass += "1st class\t"; break; case 2: pass += "2nd class\t"; break; case 3: pass += "3rd class\t"; break; case 4: pass += "crew\t"; break; pass += (child? "child": "adult") + "\t"; pass += ((sex == 'm')? "male" : "female") + "\t"; pass += (survivor? "survived": "perished"); return pass; On the next page, write the code for a PassengerCollection class to represent the list of passengers of the Titanic and to keep track of total number of passengers and survivors, using an array of Passenger objects. Some bits of the code and comments are already written. Use these comments as guidelines for your code, in the spaces provided on the next page. Note that you only need to implement the constructor and addpassenger() methods, which should initialize and update, respectively, the array and the two counts (i.e., count and numsurvivors).

(Question 7, continued) public class PassengerCollection private Passenger[] collection; private int count; private int numsurvivors; // additional count: survivors //------------------------------------------------------ // Constructor: Creates an initially empty collection // with space for up to 5000 passengers. // Initializes count and numsurvivors appropriately. //------------------------------------------------------ //------------------------------------------------------ // Method addpassenger(): Adds a Passenger to the // collection. Update // count and numsurvivors. //------------------------------------------------------ public void addpassenger (int status, boolean child, char sex, boolean survivor)

8. ( / 10) Construct an algorithm that inputs an integer num and 10,000 other integers and prints a message indicating whether num was found among the 10,000 other integers, followed by a goodbye message. Hint: You need to use a boolean variable found to keep track of whether you found a match. Example: If num (i.e., the first number input) is 1318, and 10,000 other numbers are input after that, none of which is equal to 1318, the algorithm should print: Searching for 1318 Not found Goodbye Alternatively, if the number 1318 occurred one or more times among the other numbers, it should print: Searching for 1318 Found it! Goodbye Directions: Write your algorithm by rearranging and structuring elements chosen from the list below, using indentation to show structure. Do not use anything else and note that not all of these are needed, but you may use one of them more than once, if necessar found = true found = false input num input x count = 1 count = count + 1 x = x + 1 if (x == num) if (found) if (found == true) if (found == false) if (x!=num) else while (count <= 10000) while (num <= 10000) while (count <= num) print Searching for num print x print num print Found it! print Not found print Goodbye

9. ( / 20) Write a complete Java program consisting of a datatype Cat and a client CrazyCatLady and draw a UML class diagram for your classes. Example: Ø Name: Henri Ø Age: 7 Ø Lives: 5 a) The Cat class should have the following methods: Constructor: One parameter (for the name). Sets Cat s age to 0 and lives to 9. birthday(): increases age of Cat by 1. death(): decreases the Cat s number of lives by 1. tostring(): returns a String corresponding to this Cat. getage(): returns this Cat s age draw(graphics page, int x, int y): draws this Cat in the current Graphics context at position x, y. Please do not do anything fancy here: just draw a simple shape to represent the cat and add its name nearby.add another feature such as color or different shape to depict the age or number of lives (you only need to do one of them). b) The client CrazyCatLady should implement the following algorithm: o Instantiate three variables of the Cat class named cat1, cat2, cat3 (Kindly make up funny names for them I m spending my holidays grading this exam! J ) o Print the info of cat1, cat2, cat3 Let s pretend that two years have gone by So the Cats ages need to increase. Also, cat3 has done something stupid and loses a life. Write some code that uses the birthday() and death() methods to model this situation. o Print the info of cat1, cat2, cat3 (again). o Calculate and print the average age of the cats. o NOTE: this is not a graphical class, so it does NOT use the draw() method at all. c) Draw a UML class diagram depicting the classes Cat and CrazyCatLady. Write the complete code for the two classes and UML diagram in the next 3 pages. It is NOT necessary to include comments with your code, but be sure to use good indentation. è è è