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

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

Happy Cinco de Mayo!!!!

Happy Cinco de Mayo!!!!

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 12, Name: KEY. Question Value Score

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

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

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

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

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

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

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

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

File I/O and Exceptions

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP File Access 1

I/O Streams. COMP 202 File Access. Standard I/O. I/O Stream Categories

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Arrays and File Input

Arrays and File Input

Arrays - Review. Arrays as Parameters. Arrays as Parameters. Arrays and File Input. Dr. Papalaskari 1. CSC 1051 Data Structures and Algorithms I

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

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

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

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

Arrays - Review. Initializer Lists. The for-each Loop. Arrays, Part 2. Dr. Papalaskari 1. CSC 1051 Data Structures and Algorithms I

H212 Introduction to Software Systems Honors

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

Selection Statements and operators

CSC 1051 Data Structures and Algorithms I

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

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Recitation: Loop Jul 7, 2008

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

Arrays - Review. Two-Dimensional Arrays. Arrays, Part 2. Dr. Papalaskari 1. CSC 1051 Data Structures and Algorithms I

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

7.3 Arrays of Strings (Objects) 7.3 Arrays of Strings (Objects) 7.3 Tunes.java. 7.3 Arrays of Objects 9/11/13. ! A UML diagram for the Tunes program

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

System.out.print("Enter sales for salesperson " + i + ": "); sales[i] = scan.nextint();

Lab 13. Name: Checked:

CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I

CSC 1051 Arrays - Review questions

Chapter 3. Selections

Where do objects come from? Good question!

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

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

Selection Statements and operators

Iterators and File Input

Arrays, Part 3: Multidimensional arrays

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

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

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Chapter 7. Arrays are objects that help us organize large amounts of information

CS1083 Week 2: Arrays, ArrayList

Java Coding 3. Over & over again!

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

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

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Java I/O and Control Structures

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

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

Java I/O and Control Structures Algorithms in everyday life

Algorithms and Conditionals

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP 202 File Access 1

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

Java Flow of Control

CSCI 2010 Principles of Computer Science. Basic Java Programming. 08/09/2013 CSCI Basic Java 1

COE 211 Computer Programming. Welcome to Exam I Tuesday March 13, 2018

CS Computers & Programming I Review_01 Dr. H. Assadipour

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

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

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

STUDENT LESSON A12 Iterations

Introduction to Arrays

Selection and Repetition Revisited

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

Conditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

I pledge by honor that I will not discuss this exam with anyone until my instructor reviews the exam in the class.

Full file at

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

Loops. CSE 114, Computer Science 1 Stony Brook University

Tutorial 06. Conditional statement: if then, if else, switch

This Week s Agenda (Part A) CS121: Computer Programming I. The Games People Play. Data Types & Structures. The Array in Java.

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

Problem Grade Total

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

H212 Introduction to Software Systems Honors

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

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

COE 212 Engineering Programming. Welcome to Exam I Thursday June 21, Instructor: Dr. Wissam F. Fawaz

WOSO Source Code (Java)

Transcription:

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

1. ( / 10) What gets printed? Please show output as it will appear, or indicate NO OUTPUT. If there is an infinite loop, be sure to show some lines of the output followed by INFINITE LOOP. int a = 4; do a--; System.out.println(a); while (a < 4) Output: 3 2 1 INFINITE LOOP String[] notes = "do", "re", "mi"; for (String word : notes) System.out.println ("Tra la la " + word); Output: tra la la do tra la la re tra la la mi int size = 10; do System.out.print(size + " => "); int category = size / 5; switch(category) case 0: System.out.println ("S"); break; case 1: System.out.println ("M"); break; default: System.out.println ("L"); size = size - 2; while (size > 2); Output: 10 => L 8 => M 6 => M 4 => S int a = 4; for (int a = 4; a < 4; a--) System.out.println(a); Output: NO OUTPUT

2. ( / 10) Suppose you are drawing in a Graphics context at position (x,y) an emoji that is controlled by a boolean variable happy. When happy is true, it should look like it is smiling; when false, it should look like it is frowning. Assume that the face and eyes are already drawn, so you just need to draw the mouth as an arc facing up or down. Here is the code using if/else: if (happy) page.drawarc (x+15, y+30, 20, 10, 180, 180); else page.drawarc (x+15, y+30, 20, 10, 0, 180); * Rewrite the above code using the conditional operator. (i.e., in a single line of code, without using if/else). page.drawarc (x+15, y+30, 20, 10, happy? 180: 0, 180); b) Suppose you would like to generate a random inspirational message. You start by creating an array containing a list of possible messages: String[] mycliche = "Life is beautiful", "Keep calm and carry on", "Live, laugh, love", "Today is the first day of the rest of your life" ; // add your own, if you feel like it! Write a code fragment that uses a randomly generated index into this array to print one of the above messages. Your choice whether to use an object from the Random class or the random() method from the Math class. Be sure your code works fine if you add more messages to the array (for example, if you add a fifth message in the array above). Random rand = new Random(); int choice= rand.nextint(mycliche.length); System.out.println(myCliche[choice]);

3. ( / 10) Consider the following program: //************************************************************** // SomethingToDoWithFiles.java Author: MAP //************************************************************** import java.util.scanner; import java.io.*; public class SomethingToDoWithFiles public static void main (String[] args) throws IOException String line1, line2; Scanner filescan1, filescan2; File myfile1 = new File("sample1.txt"); filescan1 = new Scanner (myfile1); File myfile2 = new File("sample2.txt"); filescan2 = new Scanner (myfile2); outfile = new PrintWriter("data-out.txt"); while (filescan1.hasnext() && filescan2.hasnext()) line1 = filescan1.nextline(); line2 = filescan2.nextline(); outfile.print(line1.charat(0) + "**" + line2.charat(0)); outfile.println(filescan2.hasnext()? "Down!": "Up!"); outfile.close(); System.out.println(fileScan2.hasNext()? "Up!": "Down!"); a) Suppose the file sample1.txt and sample2.txt are as shown above. Show the OUTPUT and the contents of the file data-out.txt after execution of the program. OUTPUT: data-out.txt Down! sample1.txt down came the rain and washed the spider out. d**ot**aw**aup! sample2.txt out came the sun and washed out all the rain b) Give an example of a situation that could cause IOExceptions in the above code. file not found for the Scanner cannot do input (OR bad file name for the PrintWriter cannot create the file)

4. ( / 10) a) Write a Java method max() with three parameters of type double that returns a value of type double that is the largest of the three given values. For example, max(35.2, 45.7, 22.8) should return 45.7. Note that the method should not print anything. public double max(double a, double b, double c) double max = a; if (b > max) max = b; if (c > max) max = c; return max; a) Write a Java method countvowels() with one parameter, a String that returns the number of vowels (an integer) in the given String. For example, countvowels("the end is near") should return 5. Note that the method should not print anything. public int countvowels(string word) int count = 0; for (char c: word) if (c == a c == e c == i c == o c == u ) count ++; return count;

5. ( / 10) a) Trace through the following code and show what gets printed. int[] a = 100, 200, 300, 400; int[] b = 1000, 2000, 3000, 4000; int[] c = b; for (int i=0; i<a.length; i++) b[i] = a[i]; a[1] = 4; b[2] = 5; c[3] = 6; for (int x: a) System.out.print(x + " "); System.out.println(); for (int x: b) System.out.print(x + " "); System.out.println(); for (int x: c) System.out.print(x + " "); System.out.println(); Output: 100 4 300 400 100 200 5 6 100 200 5 6 b) Suppose an array of int named list has been declared, instantiated, and initialized. Write a code fragment to print the contents of array list backwards. for (int i = list.length - 1; i >=0; i--) System.out.println(list[i]);

6. ( / 10) Consider the following program: // ProductCodes.java Author: Lewis/Loftus import java.util.scanner; public class ProductCodes //----------------------------------------------------------------- // Counts the number of product codes that are entered with a // zone of R and and district greater than 2000. //----------------------------------------------------------------- public static void main(string[] args) String code; char zone; int district, valid = 0, banned = 0; Scanner scan = new Scanner(System.in); System.out.print("Enter product code (XXX to quit): "); code = scan.nextline(); while (!code.equals("xxx")) try à zone = code.charat(9); catch à district = Integer.parseInt(code.substring(3, 7)); valid++; if (zone == 'R' && district > 2000) banned++; System.out.print("Enter product code (XXX to quit): "); code = scan.nextline(); System.out.println("# of valid codes entered: " + valid); System.out.println("# of banned codes entered: " + banned); a) Give a examples of product code inputs that would cause the program to _ TTTTTTTTTTTT throw a NumberFormatException TTT throw a StringIndexOutOfBoundsException AAA3446RRR NOT throw any exception but be counted as banned XXX cause the program to terminate, without error. b) Suppose you would like to catch and handle NumberFormatException by skipping this input using the following catch clause: catch (NumberFormatException exception) System.out.println("Bad code: " + code); Annotate ProductCodes.java to show exactly how the try/catch block should be placed.

7. ( / 10) Consider the following program: public class TwoDArray public static void main (String[] args) int[][] table = new int[3][9]; for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) table[row][col] = row * 10 + col; System.out.print ("# \t"); for (int col=0; col < table[0].length; col++) System.out.print (col + "\t"); System.out.println(); System.out.print ("--+-----"); for (int col=0; col < table[0].length; col++) System.out.print ("-----"); System.out.println(); for (int row=0; row < table.length; row++) System.out.print (row + " \t"); for (int col=0; col < table[row].length; col++) System.out.print (table[row][col] + "\t"); System.out.println(); We would like to modify the program to: (1) change array size; and (2) label rows/columns so that the output would now look EXACTLY like this: # 0 1 2 3 4 5 6 7 8 --+-------------------------------------------------------- 0 0 1 2 3 4 5 6 7 8 1 10 11 12 13 14 15 16 17 18 2 20 21 22 23 24 25 26 27 28 a) In the above output, circle entries corresponding to table[0][2] and table[2][3]. b) Annotate the code so that it works as described in (1) and (2) above

8. ( / 10) Complete the java code below so that it prints a table for the Investment problem: You put an initial amount into a bank account that earns 5% interest per year. Show the yearly returns on your investment until it doubles. For example, if the user inputs 10000 as the initial amount, a table such as the one shown here would be printed. import java.text.numberformat; import java.util.scanner; public class Investment public static void main (String[] args) Scanner scan = new Scanner(System.in); year interest balance 0 $10,000.00 1 $500.00 $10,500.00 2 $525.00 $11,025.00 3 $551.25 $11576.25 4 $578.81 $12,155.06 (keep going until balance >= $20000) System.out.print("Enter initial balance:"); double initial = scan.nextdouble(); int year = 0; double rate = 0.05; double balance = initial; NumberFormat money = NumberFormat.getCurrencyInstance(); System.out.println("year\tinterest\tbalance"); System.out.println (year + "\t" + " " + "\t" + money.format(balance)); double interest; double target = 2 * initial; while (balance < target) year++; interest = balance * rate; balance += interest; System.out.println (year + "\t" + money.format(interest) + "\t" + money.format(balance));

9. ( / 10) Write a complete Java program consisting of a class Shoe and a client class named Wishlist. The Shoe class should contain instance variables representing the following shoe data: manufacturer- a String, eg "Sofft" or "Steve Madden" name - a String, eg "Madeline" or "Realove" price - a f (use double), eg: 79.95 SKU number - an integer, eg: 8112951 (SKU is displayed right above price in picture below) The Shoe class should have a constructor, accessor and mutator methods for the price, and a tostring() method. Do not write code for any additional methods (no need to write accessors and mutators for all the other instance variables). The client class Wishlist should implement the following algorithm: o Instantiate three variables of the Shoe class named s1, s2, s3 (make up values for the data) o Print the info of s1, s2, s3 o Change the price of s1 to $29.99 o Print the total price of s1, s2, s3 Write the complete code for the two classes in the next two pages. Notes: It is NOT necessary to include comments with your code, but be sure to use good indentation. Formatting a number as a currency: if you need a reminder, see previous question Write the complete code for the two classes in the next two pages. èè

import java.text.numberformat; public class Shoe private String manufacturer; private String name; private double price; private int sku; // Constructor: with all the data public Shoe(String m, String n, double p, int s) manufacturer = m; name = n; price = p; sku = s; public String tostring() NumberFormat fmt = NumberFormat.getCurrencyInstance(); return name + " by " + manufacturer + ", SKU: " + sku + " " + fmt.format(price); public void setprice(double p) price = p; public double getprice() return price;

import java.text.numberformat; public class Wishlist public static void main(string[] args) Shoe s1, s2, s3, s4; s1 = new Shoe("Nike", "Air", 80, 833); s2 = new Shoe("Asics", "Gel Nimbus", 100, 329); s3 = new Shoe("Madden", "Realove", 30, 440); System.out.println(s1); System.out.println(s2); System.out.println(s3); s1.setprice(29.99); NumberFormat fmt = NumberFormat.getCurrencyInstance(); System.out.println("Total price of shoes"); double total = s1.getprice() + s2.getprice() + s3.getprice(); System.out.println(fmt.format(total));

10. ( / 10) Draw the UML class diagram for the previous problem (Shoe + Wishlist). Wishlist main(args: String[]): void Shoe manufacturer: String name: String price: double sku: int tostring: String getprice(): double setprice(x: double): void