Sorting and Searching

Size: px
Start display at page:

Download "Sorting and Searching"

Transcription

1 CHAPTER 13 Sorting and Searching The exercises in this chapter are a framework for comparing algorithms empirically. This approach provides students with a means for understanding the finer details of each sorting and search algorithm, and enables them to discover why one sorting or searching algorithm is more appropriate than another. Exercises 13-6 what happens when multiple values occur in the list to be sorted using: a) Selection sort b) Insertion sort Not Provided Trace the steps when sorting the following list: 23, 48, 49, 69, 12, 85, 20, 37, 51, 69, 23 using: a) Selection sort b) Insertion sort Java Software Solutions: Foundations of Program Design 408

2 Trace the steps when sorting the following list: 70, 60, 50, 40, 30, 20, 10 using: a) Selection sort b) Insertion sort Java Software Solutions: Foundations of Program Design 409

3 Trace the steps when sorting the following list: 11, 22, 33, 44, 55, 66, 77, 88, 99 using: a) Selection sort b) Insertion sort Java Software Solutions: Foundations of Program Design 410

4 Compare the different executions of each sort with the lists in Problem 13-2 and Problem How many comparisons are made in each? Not Provided What optimization can be performed during a linear search if the data is sorted? Once a search processes an element of the data that is greater than the key, the rest of the elements in the sorted data will be greater than the key. Therefore, the search can be terminated without processing all data elements What would happen if the list used in a binary search is not sorted? The algorithm will not work correctly. The execution of the program may not even terminate. An assumption of the binary search is that all data elements to the left of the element being examined are lesser values and all data elements to the right are greater values. If this assumption is not true, then the algorithm (assuming an incorrect ordering) will jump around erratically Why are three assignment statement necessary to exchange two values, as seen in the selection sort? What is the role of the temp variable in the selection sort example? Not Provided. Programming Projects 13-8 Modify the linear search method to optimize the search if you assume the list is sorted. In other words, don t examine any more values than you need to in order to assert that the target value is not present. ******************************************************************* Linear_Search_Test.java In Text Application Authors: Lewis and Loftus Classes: Linear_Search_Test Linear_Search ******************************************************************* Class Linear_Search_Test contains the driver of a program that searches a list of numbers using a linear search algorithm. Methods: Java Software Solutions: Foundations of Program Design 411

5 public static void main (String[] args) public class Linear_Search_Test { =========================================================== Creates an array of integers, then searches for a particular value. =========================================================== public static void main (String[] args) { int numbers[] = {7, -3, 7, 2, 8, -1, 3, 2, 5, 6, 7; System.out.println ("The index of 6 is " + Linear_Search.search (numbers, 6)); method main class Linear_Search_Test Class Linear_Search contains a static method that searches an array of integers. Methods: public static int search (int[] numbers, int target) class Linear_Search { =========================================================== Searches the specified array for target using a linear search, but assume the list is sorted in ascending order, and optimize the searching. =========================================================== public static int search (int[] numbers, int target) { int index = 0; Java Software Solutions: Foundations of Program Design 412

6 while (index < numbers.length) { if (target == numbers[index]) return index; target found else if (target > numbers[index]) return -1; index++; return -1; target not found method search class Linear_Search 13-9 Each of the sorting algorithms presented in this chapter arrange lists of number in ascending order. Rewrite the sort algorithms to arrange a list in descending order. ******************************************************************* Insertion_Sort_Test.java In Text Application Authors: Lewis and Loftus Classes: Insertion_Sort_Test Insertion_Sort ******************************************************************* Class Insertion_Sort_Test contains the driver of a program that sorts a list of numbers (descending order) using the insertion sort algorithm. Methods: public static void main (String[] args) public class Insertion_Sort_Test { =========================================================== Java Software Solutions: Foundations of Program Design 413

7 Creates an array of integers, sorts them, then prints them out. =========================================================== public static void main (String[] args) { int[] numbers = {3, 9, 6, 1, 2; Insertion_Sort.sort (numbers); for (int index = 0; index < numbers.length; index++) System.out.print (numbers[index] + " "); System.out.println (); method main class Insertion_Sort_Test Class Insertion_Sort contains a static method that sorts an array of integers in descending order. Methods: public static void sort (int[] numbers) class Insertion_Sort { =========================================================== Sorts the specified array (descending order) using insertion sort. =========================================================== public static void sort (int[] numbers) { for (int index = 1; index < numbers.length; index++) { int key = numbers[index]; int position = index; shift larger values to the left while (position > 0 && numbers[position-1] < key) { numbers[position] = numbers[position-1]; position--; Java Software Solutions: Foundations of Program Design 414

8 numbers[position] = key; method sort class Insertion_Sort ******************************************************************* Selection_Sort_Test.java In Text Application Authors: Lewis and Loftus Classes: Selection_Sort_Test Selection_Sort ******************************************************************* Class Selection_Sort_Test contains the driver of a program that sorts a list of numbers (descending order) using the selection sort algorithm. Methods: public static void main (String[] args) public class Selection_Sort_Test { =========================================================== Creates an array of integers, sorts them, then prints them out. =========================================================== public static void main (String[] args) { int[] numbers = {3, 9, 6, 1, 2; Selection_Sort.sort (numbers); Java Software Solutions: Foundations of Program Design 415

9 for (int index = 0; index < numbers.length; index++) System.out.print (numbers[index] + " "); System.out.println(); method main class Selection_Sort_Test Class Selection_Sort contains a static method that sorts an array of integers (descending order). Methods: public static void sort (int[] numbers) class Selection_Sort { =========================================================== Sorts the specified array (descending order) using selection sort. =========================================================== public static void sort (int[] numbers) { int min, temp; for (int index = 0; index < numbers.length-1; index++) { min = index; for (int scan = index+1; scan < numbers.length; scan++) if (numbers[scan] > numbers[min]) min = scan; swap the values temp = numbers[min]; numbers[min] = numbers[index]; numbers[index] = temp; for (int index1 = 0; index1 < numbers.length; index1++) System.out.print (numbers[index1] + " "); System.out.println(); Java Software Solutions: Foundations of Program Design 416

10 method sort class Selection_Sort ******************************************************************* Object_Sort_Test.java In Text Application Authors: Lewis and Loftus Classes: Object_Sort_Test Object_Sort Search_Engines Interfaces: Sortable ******************************************************************* import java.net.*; Class Object_Sort_Test contains the driver of a program that creates a sortable object (a URL list) and sorts it. Methods: public static void main (String[] args) throws MalformedURLException { public class Object_Sort_Test { =========================================================== Creates a Search_Engines object, then sorts them using the object sort method. =========================================================== public static void main (String[] args) throws MalformedURLException { Search_Engines engines = new Search_Engines(); Object_Sort.sort (engines); Java Software Solutions: Foundations of Program Design 417

11 for (int index = 0; index < engines.length(); index++) System.out.println (engines.value_at(index)); method main class Object_Sort_Test Interface Sortable lists the methods needed to sort any list of objects. Methods: boolean compare (Object left, Object right) Object value_at (int position) void set_value (Object value, int position) int length() interface Sortable { =========================================================== Should be implemented to return true if left > right. =========================================================== boolean compare (Object left, Object right); =========================================================== Should be implemented to return the object at the specified location. =========================================================== Object value_at (int position); =========================================================== Should be implemented to set the value of the specified location. =========================================================== void set_value (Object value, int position); =========================================================== Should be implemented to return the number of items in the list. Java Software Solutions: Foundations of Program Design 418

12 =========================================================== int length(); interface Sortable Class Object_Sort contains a static method that sorts any object that implements the Sortable interface. Methods: public static void sort (Sortable items) class Object_Sort { =========================================================== Sorts the specified items into descending order using an insertion sort that relys on the Sortable methods. =========================================================== public static void sort (Sortable items) { for (int index = 1; index < items.length(); index++) { Object key = items.value_at (index); int position = index; while (position > 0 &&!items.compare (items.value_at (position-1), key)) { items.set_value (items.value_at (position-1), position); position--; items.set_value (key, position); method sort class Object_Sort Class Search_Engines represents a set of URLs that can be used for web searching. The class implements the Sortable interface Java Software Solutions: Foundations of Program Design 419

13 so that the list of URLs can be sorted by host name. Constructors: public Search_Engines() throws MalformedURLException Methods: public boolean compare (Object left, Object right) public Object value_at (int index) public void set_value (Object value, int index) public int length() class Search_Engines implements Sortable { private URL[] sites = new URL[5]; =========================================================== Sets up the list of search engines. =========================================================== public Search_Engines() throws MalformedURLException { sites[0] = new URL (" sites[1] = new URL (" sites[2] = new URL (" sites[3] = new URL (" sites[4] = new URL (" constructor Search_Engines =========================================================== Returns true if the host of left is alphabetically after the host of right. =========================================================== public boolean compare (Object left, Object right) { URL site1 = (URL) left; URL site2 = (URL) right; String host1 = site1.gethost(); String host2 = site2.gethost(); Java Software Solutions: Foundations of Program Design 420

14 if (host1.compareto(host2) > 0) return true; else return false; method compare =========================================================== Returns the URL object at the specified index. =========================================================== public Object value_at (int index) { return (sites[index]); method value_at =========================================================== Sets the URL object at the specified index. =========================================================== public void set_value (Object value, int index) { sites[index] = (URL)value; method set_value =========================================================== Returns the number of URLs stored in the object. =========================================================== public int length() { return (sites.length); method length class Search_Engines Design and implement a program which reads every word of a paragraph of text and counts the occurrences of each word. Use hashing as part of the solution. ******************************************************************* Paragraph_HashTest.java In Text Applet Authors: Lewis and Loftus Classes: Paragraph_Hash_Test Paragraph_Hash Word_Object Java Software Solutions: Foundations of Program Design 421

15 ******************************************************************* import java.io.*; import java.util.*; Class Paragraph_Hash_Test contains the driver of a program that obtains a paragraph of text, places in a hash table and prints the frequency of the words contained in the paragraph. Methods: public static void main (String[] args) public class Paragraph_Hash_Test { public static void main (String [] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in)); Get the paragraph from the user and send it to the hasher System.out.println("Enter a paragraph of text: "); Paragraph_Hash.hasher (stdin.readline()); method main class Paragraph_Hash_Test Class Paragraph_Hash contains the hashing routine which accepts a String of text, places each unique word found in a Word_Object and inserts it into the hash table. Repeated words have their frequency counters incremented. When all words from the paragraph have been handled, a summary of word frequencies is printed. Methods: public static void hasher (String inputstring) Java Software Solutions: Foundations of Program Design 422

16 class Paragraph_Hash { public static void hasher(string inputstring) throws NoSuchElementException { Create a hash table to store the words Hashtable table = new Hashtable(10); Create a string tokenizer to parse the paragraph words StringTokenizer tokenizer = new StringTokenizer(inputString); while(tokenizer.hasmoretokens()) { Get the next word from the paragraph String element = tokenizer.nexttoken(); Check to see if this word is in the hash table already if (!table.containskey(element)) table.put(element, new Word_Object (element)); else ((Word_Object) table.get(element)).incrementcount(); while loop Get the enumeration of the hash table for printing Enumeration enum = table.elements(); while (enum.hasmoreelements()) System.out.println(enum.nextElement().toString()); method main class Paragraph_Hash Class Word_Object represents the data type inserted into the hash table. It will maintain the text of the hashed word and the current frequency of the word. Methods are provided for the printing of the object, incrementing the frequency counter. Methods: public Word_Object (String str) public void incrementcount () public String tostring() Java Software Solutions: Foundations of Program Design 423

17 class Word_Object { private String word; private int count; public Word_Object (String str) { word = str; count = 1; constructor Word_Object public void incrementcount () { count++; method incrementcount public String tostring () { return ("Word = " + word + " method tostring frequency = " + count); class Word_Object Design and implement a program which sorts a list of People objects, each of which contains a name, age, and salary. Allow the list to be sorted by any of these values, depending on the sort method invoked. ******************************************************************* People_Sort_Test.java In Text Application Authors: Lewis and Loftus Classes: People_Sort_Test People People_Sort ******************************************************************* Class People_Sort_Test contains the driver of a program that sorts a list of people using the insertion sort algorithm. Methods: Java Software Solutions: Foundations of Program Design 424

18 public static void main (String[] args) public class People_Sort_Test { =========================================================== Creates an array of People, sorts them, then prints them out. =========================================================== public static void main (String[] args) { People[] my_friends = { new People ("Pete DePasquale", 29, 31000), new People ("Sam Perugini", 20, 15000), new People ("Thomas Standish", 35, 45000), new People ("Grady Booch", 19, 30000), new People ("Fred Brooks", 45, ) ; System.out.println("\n\nPeople sorted by names:"); System.out.println("==============================="); People_Sort.sort_By_Name (my_friends); for (int index = 0; index < my_friends.length; index++) System.out.println (my_friends[index].tostring()); System.out.println("\n\nPeople sorted by age:"); System.out.println("==============================="); People_Sort.sort_By_Age (my_friends); for (int index = 0; index < my_friends.length; index++) System.out.println (my_friends[index].tostring()); System.out.println("\n\nPeople sorted by salary:"); System.out.println("==============================="); People_Sort.sort_By_Salary (my_friends); for (int index = 0; index < my_friends.length; index++) System.out.println (my_friends[index].tostring()); method main Java Software Solutions: Foundations of Program Design 425

19 class People_Sort_Test Class People contains a person's name, age and salary information. Access methods to obtain the name, age and salary are provided as well as a tostring method to print the contents all on one line. Methods: public People(String nm, int ag, int sal) public String tostring() public String getname() public int getage() public int getsalary() class People { private String name; private int age; private int salary; public People(String nm, int ag, int sal) { name = nm; age = ag; salary = sal; People constructor public String tostring() { return (name + " " + age + " $" + salary); method tostring public String getname() { return name; method getname Java Software Solutions: Foundations of Program Design 426

20 public int getage() { return age; method getage public int getsalary() { return salary; method getsalary class People Class People_Sort contains a static method that sorts an array of People. Methods: public static void sort_by_name (People[] friends) public static void sort_by_age (People[] friends) public static void sort_by_salary (People[] friends) class People_Sort { =========================================================== Sorts the specified array (by person's name) using insertion sort. =========================================================== public static void sort_by_name (People[] friends) { for (int index = 1; index < friends.length; index++) { People key = friends[index]; int position = index; shift larger values to the right while (position > 0 && friends[position-1].getname(). compareto(key.getname()) > 0) { friends[position] = friends[position-1]; position--; Java Software Solutions: Foundations of Program Design 427

21 friends[position] = key; method sort_by_name =========================================================== Sorts the specified array (by person's age) using insertion sort. =========================================================== public static void sort_by_age (People[] friends) { for (int index = 1; index < friends.length; index++) { People key = friends[index]; int position = index; shift larger values to the right while (position > 0 && friends[position-1].getage() > key.getage()) { friends[position] = friends[position-1]; position--; friends[position] = key; method sort_by_age =========================================================== Sorts the specified array (by person's salary) using insertion sort. =========================================================== public static void sort_by_salary (People[] friends) { for (int index = 1; index < friends.length; index++) { People key = friends[index]; int position = index; shift larger values to the right while (position > 0 && friends[position-1].getsalary() > key.getsalary()) { Java Software Solutions: Foundations of Program Design 428

22 friends[position] = friends[position-1]; position--; friends[position] = key; method sort_by_salary class People_Sort Design and implement a generic binary search algorithm. Exercise the class by storing a list of employees, and searching for individuals by name. ******************************************************************* Employee_Search_Test.java In Text Application Authors: Lewis and Loftus Classes: Employee_Search_Test Employee Object_Binary_Search ******************************************************************* import java.io.*; Class Employee_Sort_Test contains the driver of a program that searches a list of employees for a particular employee and prints that person's information. Methods: public static void main (String[] args) public class Employee_Search_Test { Java Software Solutions: Foundations of Program Design 429

23 =========================================================== Creates an array of Employees, and then searches for a specific individual. =========================================================== public static void main (String[] args) throws IOException { BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in)); Employee[] subordinates = { new Employee ("Fred Brooks", 45, ), new Employee ("Grady Booch", 19, 30000), new Employee ("Pete DePasquale", 29, 31000), new Employee ("Sam Perugini", 20, 15000), new Employee ("Thomas Standish", 35, 45000) ; System.out.print ("Enter the name of the person to seach for: "); int result = Object_Binary_Search.search(subordinates, stdin.read- Line()); if (result == -1) System.out.println("\nSearch failed."); else System.out.println("\n" + subordinates[result].tostring()); method main class Employee_Search_Test Interface Searchable lists the method needed to compare any list of objects during a search operation Methods: boolean compare (Object left, Object right) interface Searchable { Java Software Solutions: Foundations of Program Design 430

24 =========================================================== Should be implemented to return 0 if this = target, 1 if this > target and -1 if this < target =========================================================== int compare (Object target); interface Searchable Class Employee contains a person's name, age and salary information. Access methods to obtain the name, age and salary are provided as well as a tostring method to print the contents all on one line and a comparison method. Methods: public Employee (String nm, int ag, int sal) public String tostring () public String getname () public int getage () public int getsalary () public boolean compare (Object obj) class Employee implements Searchable { private String name; private int age; private int salary; public Employee(String nm, int ag, int sal) { name = nm; age = ag; salary = sal; People constructor =========================================================== Returns the string representation of this object =========================================================== Java Software Solutions: Foundations of Program Design 431

25 public String tostring () { return (name + " " + age + " $" + salary); method tostring =========================================================== Returns the name of the employee =========================================================== public String getname () { return name; method getname =========================================================== Returns the age of the employee =========================================================== public int getage () { return age; method getage =========================================================== Returns the salary of the employee =========================================================== public int getsalary () { return salary; method getsalary =========================================================== Returns 0 if this = target, 1 if this > target and -1 if this < target =========================================================== public int compare (Object obj) { int comparison_result; if (obj instanceof String) comparison_result = name.compareto((string) obj); else comparison_result = 0; if (comparison_result > 0) return 1; else Java Software Solutions: Foundations of Program Design 432

26 return -1; method compare =========================================================== Returns true if this Employee's name is equal to target =========================================================== public boolean equals(object target) { if (this.name.equals((string) target)) return true; else return false; class Employee Class Object_Binary_Search contains a static method that searches an array of Objects. Methods: public static int search (Object[] numbers, Object target) class Object_Binary_Search { =========================================================== Searches the specified array for target using a binary search. =========================================================== public static int search (Searchable[] items, Object target) { int index; int left = 0, right = items.length - 1; while (left <= right) { index = (left + right) / 2; if (items[index].equals(target)) return index; target found Java Software Solutions: Foundations of Program Design 433

27 if (items[index].compare(target) < 0) left = index + 1; else right = index - 1; return -1; target not found method search class Object_Binary_Search Modify the algorithms for the selection sort and the insertion sort to count the: Number of comparisons Number of exchanges Number of times each loop is executed ******************************************************************* Insertion_Sort_Test2.java In Text Application Authors: Lewis and Loftus Classes: Insertion_Sort_Test Insertion_Sort ******************************************************************* Class Insertion_Sort_Test2 contains the driver of a program that sorts a list of numbers using the insertion sort algorithm. Methods: public static void main (String[] args) public class Insertion_Sort_Test2 { Java Software Solutions: Foundations of Program Design 434

28 =========================================================== Creates an array of integers, sorts them, then prints them out. =========================================================== public static void main (String[] args) { int[] numbers = new int[4000]; for (int index = 0; index < numbers.length; index++) { numbers[index] = (int)(math.random()*100000); Insertion_Sort2.sort (numbers); for (int index = 0; index < numbers.length; index++) System.out.println (numbers[index]); Insertion_Sort2.printSummary(); method main class Insertion_Sort_Test Class Insertion_Sort contains a static method that sorts an array of integers. Methods: public static void sort (int[] numbers) public static void printsummary () class Insertion_Sort2 { public static int numberofcomparisons; public static int numberofexchanges; public static int numberofloopexecutions; =========================================================== Sorts the specified array using insertion sort. =========================================================== Java Software Solutions: Foundations of Program Design 435

29 public static void sort (int[] numbers) { numberofcomparisons = numberofexchanges = numberofloopexecutions = 0; for (int index = 1; index < numbers.length; index++) { int key = numbers[index]; int position = index; shift larger values to the right while (position > 0 && numbers[position-1] > key) { numbers[position] = numbers[position-1]; position--; numberofcomparisons++; numberofexchanges++; numberofloopexecutions++; numbers[position] = key; numberofexchanges++; method sort =========================================================== Prints the statistics of the sort. =========================================================== public static void printsummary () { System.out.println("The total number of comparisons was: " + numberofcomparisons); System.out.println("The total number of exchanges was: " + numberofexchanges); System.out.println("The total number of loop executions was: " + numberofloopexecutions); method printsummary class Insertion_Sort ******************************************************************* Selection_Sort_Test2.java In Text Application Java Software Solutions: Foundations of Program Design 436

30 Authors: Lewis and Loftus Classes: Selection_Sort_Test Selection_Sort ******************************************************************* Class Selection_Sort_Test2 contains the driver of a program that sorts a list of numbers using the selection sort algorithm. Methods: public static void main (String[] args) public class Selection_Sort_Test2 { =========================================================== Creates an array of integers, sorts them, then prints them out. =========================================================== public static void main (String[] args) { int[] numbers = new int[4000]; for (int index = 0; index < numbers.length; index++) { numbers[index] = (int)(math.random()*100); long start = System.currentTimeMillis(); Selection_Sort2.sort (numbers); long stop = System.currentTimeMillis(); System.out.println ("Time is " + (stop - start)); for (int index = 0; index < numbers.length; index++) System.out.println (numbers[index]); Selection_Sort2.printSummary(); method main Java Software Solutions: Foundations of Program Design 437

31 class Selection_Sort_Test Class Selection_Sort contains a static method that sorts an array of integers. Methods: public static void sort (int[] numbers) public static void printsummary () class Selection_Sort2 { public static int numberofcomparisons; public static int numberofexchanges; public static int numberofloopexecutions; =========================================================== Sorts the specified array using selection sort. =========================================================== public static void sort (int[] numbers) { int min, temp; numberofcomparisons = numberofexchanges = numberofloopexecutions = 0; for (int index = 0; index < numbers.length-1; index++) { numberofloopexecutions++; min = index; for (int scan = index+1; scan < numbers.length; scan++) { numberofcomparisons++; if (numbers[scan] < numbers[min]) { min = scan; swap the values temp = numbers[min]; numbers[min] = numbers[index]; Java Software Solutions: Foundations of Program Design 438

32 numbers[index] = temp; numberofexchanges++; method sort =========================================================== Prints the statistics of the sort. =========================================================== public static void printsummary () { System.out.println("The total number of comparisons was: " + numberofcomparisons); System.out.println("The total number of exchanges was: " + numberofexchanges); System.out.println("The total number of loop executions was: " + numberofloopexecutions); method printsummary class Selection_Sort Java Software Solutions: Foundations of Program Design 439

Sorting & Searching (and a Tower)

Sorting & Searching (and a Tower) Sorting & Searching (and a Tower) Sorting Sorting is the process of arranging a list of items into a particular order There must be some value on which the order is based There are many algorithms for

More information

Sorting/Searching and File I/O

Sorting/Searching and File I/O Sorting/Searching and File I/O Sorting Searching CLI: File Input CLI: File Output GUI: File Chooser Reading for this lecture: 13.1 (and other sections of Chapter 13) 1 Sorting Sorting is the process of

More information

Searching and Sorting (Savitch, Chapter 7.4)

Searching and Sorting (Savitch, Chapter 7.4) Searching and Sorting (Savitch, Chapter 7.4) TOPICS Algorithms Complexity Binary Search Bubble Sort Insertion Sort Selection Sort What is an algorithm? A finite set of precise instruc6ons for performing

More information

What is an algorithm?

What is an algorithm? /0/ What is an algorithm? Searching and Sorting (Savitch, Chapter 7.) TOPICS Algorithms Complexity Binary Search Bubble Sort Insertion Sort Selection Sort A finite set of precise instrucons for performing

More information

ECM1406. Answer Sheet Lists

ECM1406. Answer Sheet Lists ECM1406 Answer Sheet Lists These questions are based on those found in Chapters 3 and 4 of the core text Data Structures Using Java by Malik and Nair. The source code for the ArrayListClass, UnorderedArrayList,

More information

1. Download the JDK 6, from

1. Download the JDK 6, from 1. Install the JDK 1. Download the JDK 6, from http://java.sun.com/javase/downloads/widget/jdk6.jsp. 2. Once the file is completed downloaded, execute it and accept the license agreement. 3. Select the

More information

Exercise 4: Loops, Arrays and Files

Exercise 4: Loops, Arrays and Files Exercise 4: Loops, Arrays and Files worth 24% of the final mark November 4, 2004 Instructions Submit your programs in a floppy disk. Deliver the disk to Michele Zito at the 12noon lecture on Tuesday November

More information

Programming 2. Topic 8: Linked Lists, Basic Searching and Sorting

Programming 2. Topic 8: Linked Lists, Basic Searching and Sorting RMIT School of Computer Science and Information Technology Programming 2 Topic 8: Linked Lists, Basic Searching and Sorting Lecture Slides COPYRIGHT 2008 RMIT University. Original content by: Peter Tilmanis,

More information

Classes Basic Overview

Classes Basic Overview Final Review!!! Classes and Objects Program Statements (Arithmetic Operations) Program Flow String In-depth java.io (Input/Output) java.util (Utilities) Exceptions Classes Basic Overview A class is a container

More information

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O

I/O in Java I/O streams vs. Reader/Writer. HW#3 due today Reading Assignment: Java tutorial on Basic I/O I/O 10-7-2013 I/O in Java I/O streams vs. Reader/Writer HW#3 due today Reading Assignment: Java tutorial on Basic I/O public class Swimmer implements Cloneable { public Date geteventdate() { return (Date)

More information

Unit 10: Sorting/Searching/Recursion

Unit 10: Sorting/Searching/Recursion Unit 10: Sorting/Searching/Recursion Notes AP CS A Searching. Here are two typical algorithms for searching a collection of items (which for us means an array or a list). A Linear Search starts at the

More information

4. Finding & Displaying Record of Salesman with minimum net income. 5. Finding & Displaying Record of Salesman with maximum net income.

4. Finding & Displaying Record of Salesman with minimum net income. 5. Finding & Displaying Record of Salesman with maximum net income. Solution of problem#55 of Lab Assignment Problem Statement: Design & Implement a java program that can handle salesmen records of ABC Company. Each salesman has unique 4 digit id #, name, salary, monthly

More information

Sorting/Searching and File I/O. Sorting Searching Reading for this lecture: L&L

Sorting/Searching and File I/O. Sorting Searching Reading for this lecture: L&L Sorting/Searching and File I/O Sorting Searching Reading for this lecture: L&L 10.4-10.5 1 Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based

More information

Lab 11. A sample of the class is:

Lab 11. A sample of the class is: Lab 11 Lesson 11-2: Exercise 1 Exercise 2 A sample of the class is: public class List // Methods public void store(int item) values[length] = item; length++; public void printlist() // Post: If the list

More information

e) Implicit and Explicit Type Conversion Pg 328 j) Types of errors Pg 371

e) Implicit and Explicit Type Conversion Pg 328 j) Types of errors Pg 371 Class IX HY 2013 Revision Guidelines Page 1 Section A (Power Point) Q1.What is PowerPoint? How are PowerPoint files named? Q2. Describe the 4 different ways of creating a presentation? (2 lines each) Q3.

More information

Lecture #8-10 Arrays

Lecture #8-10 Arrays Lecture #8-10 Arrays 1. Array data structure designed to store a fixed-size sequential collection of elements of the same type collection of variables of the same type 2. Array Declarations Creates a Storage

More information

University of Palestine. Mid Exam Total Grade: 100

University of Palestine. Mid Exam Total Grade: 100 First Question No. of Branches (5) A) Choose the correct answer: 1. If we type: system.out.println( a ); in the main() method, what will be the result? int a=12; //in the global space... void f() { int

More information

H212 Introduction to Software Systems Honors

H212 Introduction to Software Systems Honors Introduction to Software Systems Honors Lecture #04: Fall 2015 1/20 Office hours Monday, Wednesday: 10:15 am to 12:00 noon Tuesday, Thursday: 2:00 to 3:45 pm Office: Lindley Hall, Room 401C 2/20 Printing

More information

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004 1.00/1.001 Introduction to Computers and Engineering Problem Solving Final / December 13, 2004 Name: Email Address: TA: Section: You have 180 minutes to complete this exam. For coding questions, you do

More information

10/21/ Linear Search The linearsearch Algorithm Binary Search The binarysearch Algorithm

10/21/ Linear Search The linearsearch Algorithm Binary Search The binarysearch Algorithm 13.1 Linear Search! A linear search simply examines each item in the search pool, one at a time, until either the target is found or until the pool is exhausted! This approach does not assume the items

More information

Sorting. Task Description. Selection Sort. Should we worry about speed?

Sorting. Task Description. Selection Sort. Should we worry about speed? Sorting Should we worry about speed? Task Description We have an array of n values in any order We need to have the array sorted in ascending or descending order of values 2 Selection Sort Select the smallest

More information

Recursion. General Algorithm for Recursion. When to use and not use Recursion. Recursion Removal. Examples

Recursion. General Algorithm for Recursion. When to use and not use Recursion. Recursion Removal. Examples Recursion General Algorithm for Recursion When to use and not use Recursion Recursion Removal Examples Comparison of the Iterative and Recursive Solutions Exercises Unit 19 1 General Algorithm for Recursion

More information

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616 OBJECT ORIENTED PROGRAMMING Course 4 Loredana STANCIU loredana.stanciu@upt.ro Room B616 Inheritance A class that is derived from another class is called a subclass (also a derived class, extended class,

More information

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers;

Arrays. Here is the generic syntax for an array declaration: type[] <var_name>; Here's an example: int[] numbers; Arrays What are they? An array is a data structure that holds a number of related variables. Thus, an array has a size which is the number of variables it can store. All of these variables must be of the

More information

a) Answer all questions. b) Write your answers in the space provided. c) Show all calculations where applicable.

a) Answer all questions. b) Write your answers in the space provided. c) Show all calculations where applicable. Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2008 January Exam Question Max Internal

More information

A Guide Illustrating the Core Java Equivalent to Selected Tasks Done Using the HSA Class Library

A Guide Illustrating the Core Java Equivalent to Selected Tasks Done Using the HSA Class Library HSA to Core Java A Guide Illustrating the Core Java Equivalent to Selected Tasks Done Using the HSA Class Library The examples below compare how tasks are done using the hsa Console class with how they

More information

20 Standard API: Math: round() 21 Salary analysis 22 Standard API: System: out.printf(): string item 24 Standard API: System: out.printf(): fixed text

20 Standard API: Math: round() 21 Salary analysis 22 Standard API: System: out.printf(): string item 24 Standard API: System: out.printf(): fixed text List of Slides 1 Title 2 Chapter 14: Arrays 3 Chapter aims 4 Section 2: Example:Salary analysis 5 Aim 6 Salary analysis 7 Salary analysis 8 Array 10 Type: array type 11 Salary analysis 12 Variable: of

More information

CSC 1051 Data Structures and Algorithms I

CSC 1051 Data Structures and Algorithms I Repetition CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in this

More information

CIS 110: Introduction to computer programming

CIS 110: Introduction to computer programming CIS 110: Introduction to computer programming Lecture 25 Inheritance and polymorphism ( 9) 12/3/2011 CIS 110 (11fa) - University of Pennsylvania 1 Outline Inheritance Polymorphism Interfaces 12/3/2011

More information

Topics. Sorting. Sorting. 1) How can we sort data in an array? a) Selection Sort b) Insertion Sort

Topics. Sorting. Sorting. 1) How can we sort data in an array? a) Selection Sort b) Insertion Sort Topics 1) How can we sort data in an array? a) Selection Sort b) Insertion Sort 2) How can we search for an element in an array? a) Linear Search b) Binary Search Slides #15 Sections 9.1-9.5 Sorting and

More information

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

CSC 1051 Algorithms and Data Structures I. Final Examination May 2, Name: 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.

More information

Selection Statements and operators

Selection Statements and operators Selection Statements and operators CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

More information

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

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name CSC 1051 Algorithms and Data Structures I Final Examination May 12, 2017 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.

More information

Course Content. Objectives of Lecture 18 Black box testing and planned debugging. Outline of Lecture 18

Course Content. Objectives of Lecture 18 Black box testing and planned debugging. Outline of Lecture 18 Structural Programming and Data Structures Winter 2000 CMPUT 102: Testing and Debugging Dr. Osmar R. Zaïane Course Content Introduction Objects Methods Tracing Programs Object State Sharing resources Selection

More information

Assignment2013 Please use this document only for verifying if your programs are right. Do not blindly copy paste and waste your time.

Assignment2013 Please use this document only for verifying if your programs are right. Do not blindly copy paste and waste your time. Please use this document only for verifying if your programs are right. Do not blindly copy paste and waste your time. 11/3/2013 TechSparx Computer Training Center Saravanan.G Please use this document

More information

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each Your Name: Your Pitt (mail NOT peoplesoft) ID: Part Question/s Points available Rubric Your Score A 1-6 6 1 pt each B 7-12 6 1 pt each C 13-16 4 1 pt each D 17-19 5 1 or 2 pts each E 20-23 5 1 or 2 pts

More information

A sample print out is: is is -11 key entered was: w

A sample print out is: is is -11 key entered was: w Lab 9 Lesson 9-2: Exercise 1, 2 and 3: Note: when you run this you may need to maximize the window. The modified buttonhandler is: private static class ButtonListener implements ActionListener public void

More information

Page 1 / 3. Page 2 / 18. Page 3 / 8. Page 4 / 21. Page 5 / 15. Page 6 / 20. Page 7 / 15. Total / 100. Pledge:

Page 1 / 3. Page 2 / 18. Page 3 / 8. Page 4 / 21. Page 5 / 15. Page 6 / 20. Page 7 / 15. Total / 100. Pledge: This pledged exam is open text book and closed notes. Different questions have different points associated with them. Because your goal is to maximize your number of points, we recommend that you do not

More information

Getting Started in Java. Bill Pugh Dept. of Computer Science Univ. of Maryland, College Park

Getting Started in Java. Bill Pugh Dept. of Computer Science Univ. of Maryland, College Park Getting Started in Java Bill Pugh Dept. of Computer Science Univ. of Maryland, College Park Hello, World In HelloWorld.java public class HelloWorld { public static void main(string [] args) { System.out.println(

More information

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000 The Object Class Mark Allen Weiss Copyright 2000 1/4/02 1 java.lang.object All classes either extend Object directly or indirectly. Makes it easier to write generic algorithms and data structures Makes

More information

Input from Files. Buffered Reader

Input from Files. Buffered Reader Input from Files Buffered Reader Input from files is always text. You can convert it to ints using Integer.parseInt() We use BufferedReaders to minimize the number of reads to the file. The Buffer reads

More information

Selection Statements and operators

Selection Statements and operators Selection Statements and operators CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

More information

Java Flow of Control

Java Flow of Control Java Flow of Control SEEM 3460 1 Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence Some programming statements

More information

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.

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. Grading Page 1 / 4 Page3 / 20 Page 4 / 13 Page 5 / 10 Page 6 / 26 Page 7 / 17 Page 8 / 10 Total / 100 1. (4 points) What is your course section? CS 101 CS 101E Pledged Page 1 of 8 Pledged The following

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer

Prelim 1 SOLUTION. CS 2110, September 29, 2016, 7:30 PM Total Question Name Loop invariants. Recursion OO Short answer Prelim 1 SOLUTION CS 2110, September 29, 2016, 7:30 PM 0 1 2 3 4 5 Total Question Name Loop invariants Recursion OO Short answer Exception handling Max 1 15 15 25 34 10 100 Score Grader 0. Name (1 point)

More information

Java Coding 3. Over & over again!

Java Coding 3. Over & over again! Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java

More information

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 Arrays, Part 2 CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some slides in

More information

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

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Arrays CSC 2014 Java Bootcamp Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Some slides in this presentation are adapted from the slides accompanying Java Software Solutions

More information

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

Arrays - Review. Initializer Lists. The for-each Loop. Arrays, Part 2. Dr. Papalaskari 1. CSC 1051 Data Structures and Algorithms I Arrays, Part 2 Arrays - Review Declaration: double[] scores element type Instantiation: = new double[10]; CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences

More information

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

University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ Test 2. Question Max Mark Internal External Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2009 Test 2 Question Max Mark Internal

More information

Chapter 6: Arrays. Presentation slides for. Java Software Solutions. for AP* Computer Science 3rd Edition

Chapter 6: Arrays. Presentation slides for. Java Software Solutions. for AP* Computer Science 3rd Edition Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition by John Lewis, William Loftus, and Cara Cocking Java Software Solutions is published by Addison-Wesley

More information

Stacks Goodrich, Tamassia

Stacks Goodrich, Tamassia Stacks Abstract Data Types (ADTs) An abstract data type (ADT) is an abstraction of a data structure An ADT specifies: Data stored Operations on the data Error conditions associated with operations Example:

More information

University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ June Exam

University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ June Exam Name: Please fill in your Student Number and Name. Student Number : Student Number: University of Cape Town ~ Department of Computer Science Computer Science 1015F ~ 2009 June Exam Question Max Internal

More information

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 12, Name: KEY. Question Value Score CSC 1051 Algorithms and Data Structures I Final Examination May 12, 2017 Name: KEY 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

More information

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade; Control Statements Control Statements All programs could be written in terms of only one of three control structures: Sequence Structure Selection Structure Repetition Structure Sequence structure The

More information

11/19/2014. Arrays. Chapter 6: Arrays. Arrays. Arrays. Java Software Solutions for AP* Computer Science A 2nd Edition

11/19/2014. Arrays. Chapter 6: Arrays. Arrays. Arrays. Java Software Solutions for AP* Computer Science A 2nd Edition Chapter 6: Arrays Arrays An array is an ordered list of values Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis, William Loftus, and Cara Cocking The

More information

Sorting and Searching

Sorting and Searching Sorting and Searching Sorting o Simple: Selection Sort and Insertion Sort o Efficient: Quick Sort and Merge Sort Searching o Linear o Binary Reading for this lecture: http://introcs.cs.princeton.edu/python/42sort/

More information

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004

1.00/ Introduction to Computers and Engineering Problem Solving. Final / December 13, 2004 1.00/1.001 Introduction to Computers and Engineering Problem Solving Final / December 13, 2004 Name: Email Address: TA: Solution Section: You have 180 minutes to complete this exam. For coding questions,

More information

CS 113 MIDTERM EXAM 2 SPRING 2013

CS 113 MIDTERM EXAM 2 SPRING 2013 CS 113 MIDTERM EXAM 2 SPRING 2013 There are 18 questions on this test. The value of each question is: 1-15 multiple choice (3 pts) 17 coding problem (15 pts) 16, 18 coding problems (20 pts) You may get

More information

Full file at

Full file at Chapter 1 Primitive Java Weiss 4 th Edition Solutions to Exercises (US Version) 1.1 Key Concepts and How To Teach Them This chapter introduces primitive features of Java found in all languages such as

More information

Computer Science 1 Bh

Computer Science 1 Bh UNIVERSITY OF EDINBURGH course CS0077 FACULTY OF SCIENCE AND ENGINEERING DIVISION OF INFORMATICS SCHOOL OF COMPUTER SCIENCE Computer Science 1 Bh Degree Examination Date: Saturday 25th May 2002 Time: 12:00

More information

Iterators and File Input

Iterators and File Input Iterators and File Input CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some

More information

&KDSWHU$UUD\VDQG9HFWRUV

&KDSWHU$UUD\VDQG9HFWRUV &KDSWHU$UUD\VDQG9HFWRUV Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus Java Software Solutions is published by Addison-Wesley

More information

CS1083 Week 2: Arrays, ArrayList

CS1083 Week 2: Arrays, ArrayList CS1083 Week 2: Arrays, ArrayList mostly review David Bremner 2018-01-08 Arrays (1D) Declaring and using 2D Arrays 2D Array Example ArrayList and Generics Multiple references to an array d o u b l e prices

More information

WES-CS GROUP MEETING #9

WES-CS GROUP MEETING #9 WES-CS GROUP MEETING #9 Exercise 1: Practice Multiple-Choice Questions 1. What is output when the following code executes? String S1 = new String("hello"); String S2 = S1 +! ; S1 = S1 + S1; System.out.println(S1);

More information

CSC 273 Data Structures

CSC 273 Data Structures CSC 273 Data Structures Lecture 5 - Introduction to Sorting The Interface Comparable Consider the method compareto for class String if s and t are strings, s.compareto(t) is Negative if s comes before

More information

Selection and Repetition Revisited

Selection and Repetition Revisited Selection and Repetition Revisited CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

More information

Instance Method Development Demo

Instance Method Development Demo Instance Method Development Demo Write a class Person with a constructor that accepts a name and an age as its argument. These values should be stored in the private attributes name and age. Then, write

More information

Input & Output in Java. Standard I/O Exception Handling

Input & Output in Java. Standard I/O Exception Handling Input & Output in Java Standard I/O Exception Handling Java I/O: Generic & Complex Java runs on a huge variety of plaforms to accomplish this, a Java Virtual Machine (JVM) is written for every type of

More information

i219 Software Design Methodology 8. Dynamic modeling 1 Kazuhiro Ogata (JAIST) Outline of lecture

i219 Software Design Methodology 8. Dynamic modeling 1 Kazuhiro Ogata (JAIST) Outline of lecture i219 Software Design Methodology 8. Dynamic modeling 1 Kazuhiro Ogata (JAIST) Outline of lecture 2 Use case Use case diagram State (machine) diagram Sequence diagram Class diagram of vending machine Vending

More information

Polymorphism. return a.doublevalue() + b.doublevalue();

Polymorphism. return a.doublevalue() + b.doublevalue(); Outline Class hierarchy and inheritance Method overriding or overloading, polymorphism Abstract classes Casting and instanceof/getclass Class Object Exception class hierarchy Some Reminders Interfaces

More information

Outline. 15. Inheritance. Programming in Java. Computer Science Dept Va Tech August D Barnette, B Keller & P Schoenhoff

Outline. 15. Inheritance. Programming in Java. Computer Science Dept Va Tech August D Barnette, B Keller & P Schoenhoff Outline 1 Inheritance: extends ; Superclasses and Subclasses Valid and invalid object states, & Instance variables: protected Inheritance and constructors, super The is-a vs. has-a relationship (Inheritance

More information

Chapter 5 Some useful classes

Chapter 5 Some useful classes Chapter 5 Some useful classes Lesson page 5-1. Numerical wrapper classes Activity 5-1-1 Wrapper-class Integer Question 1. False. A new Integer can be created, but its contents cannot be changed. Question

More information

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

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

CN208 Introduction to Computer Programming

CN208 Introduction to Computer Programming CN208 Introduction to Computer Programming Lecture #11 Streams (Continued) Pimarn Apipattanamontre Email: pimarn@pimarn.com 1 The Object Class The Object class is the direct or indirect superclass of every

More information

Chapter. Let's explore some other fundamental programming concepts

Chapter. Let's explore some other fundamental programming concepts Data and Expressions 2 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Data and Expressions Let's explore some

More information

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

System.out.print(Enter sales for salesperson  + i + : ); sales[i] = scan.nextint(); Tracking Sales File Sales.java contains a Java program that prompts for and reads in the sales for each of 5 salespeople in a company. It then prints out the id and amount of sales for each salesperson

More information

QUEEN MARY, UNIVERSITY OF LONDON DCS128 ALGORITHMS AND DATA STRUCTURES Class Test Monday 27 th March

QUEEN MARY, UNIVERSITY OF LONDON DCS128 ALGORITHMS AND DATA STRUCTURES Class Test Monday 27 th March QUEEN MARY, UNIVERSITY OF LONDON DCS128 ALGORITHMS AND DATA STRUCTURES Class Test Monday 27 th March 2006 11.05-12.35 Please fill in your Examination Number here: Student Number here: MODEL ANSWERS All

More information

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

McGill University School of Computer Science COMP-202A Introduction to Computing 1 McGill University School of Computer Science COMP-202A Introduction to Computing 1 Midterm Exam Thursday, October 26, 2006, 18:00-20:00 (6:00 8:00 PM) Instructors: Mathieu Petitpas, Shah Asaduzzaman, Sherif

More information

Problem Grade Total

Problem Grade Total CS 101, Prof. Loftin: Final Exam, May 11, 2009 Name: All your work should be done on the pages provided. Scratch paper is available, but you should present everything which is to be graded on the pages

More information

First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010

First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010 First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010 NAME (Printed) NAME (Signed) E-mail Exam Rules Show all your work. Your grade will be

More information

CS 101 Exam 2 Spring Id Name

CS 101 Exam 2 Spring Id Name CS 101 Exam 2 Spring 2005 Email Id Name This exam is open text book and closed notes. Different questions have different points associated with them. Because your goal is to maximize your number of points,

More information

The class Object. Lecture CS1122 Summer 2008

The class Object.  Lecture CS1122 Summer 2008 The class Object http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html Lecture 10 -- CS1122 Summer 2008 Review Object is at the top of every hierarchy. Every class in Java has an IS-A relationship

More information

Byte and Character Streams. Reading and Writing Console input and output

Byte and Character Streams. Reading and Writing Console input and output Byte and Character Streams Reading and Writing Console input and output 1 I/O basics The io package supports Java s basic I/O (input/output) Java does provide strong, flexible support for I/O as it relates

More information

Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination

Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination November 7th, 2012 Examiners: Daniel Pomerantz [Sections

More information

Question 1a) Trace of program

Question 1a) Trace of program Question 1a) What is printed by the following Java program? int s; int r; int i; int [] x = 4, 8, 2, -9, 6; s = 1; r = 0; i = x.length - 1; while (i > 0) s = s * -1; i = i - 1; r = r + s * x[i]; System.out.println(r);

More information

Searching and Sorting Chapter 18. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Searching and Sorting Chapter 18. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Searching and Sorting Chapter 18 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Scope 2 Searching and Sorting: Linear search and binary search algorithms Several sorting algorithms,

More information

CSE 143 Lecture 25. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides adapted from Marty Stepp

CSE 143 Lecture 25. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides adapted from Marty Stepp CSE 143 Lecture 25 I/O Streams; Exceptions; Inheritance read 9.3, 6.4 slides adapted from Marty Stepp http://www.cs.washington.edu/143/ Input and output streams stream: an abstraction of a source or target

More information

Selection and Repetition Revisited

Selection and Repetition Revisited Selection and Repetition Revisited CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

More information

Do not open this examination paper until instructed to do so. Section A: answer all the questions. Section B: answer all the questions.

Do not open this examination paper until instructed to do so. Section A: answer all the questions. Section B: answer all the questions. M09/5/COMSC/SP1/ENG/TZ0/XX 22097013 Computer science Standard level Paper 1 Tuesday 19 May 2009 (afternoon) 1 hour 30 minutes INSTRUCTIONS TO CANDIDATES Do not open this examination paper until instructed

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1(c): Java Basics (II) Lecture Contents Java basics (part II) Conditions Loops Methods Conditions & Branching Conditional Statements A

More information

for (int outercounter = nums.length - 1; outercounter > 0 && swappedthatturn; outercounter --

for (int outercounter = nums.length - 1; outercounter > 0 && swappedthatturn; outercounter -- /* * A small set of sorting algorithms, written in Java and C++ * Note that they are written by a C++ beginner, may contain mistakes * Or bad habits that have to be avoided * @author Kadir Can Çelik */

More information

COS 126 Written Exam 2 (Spring 2015)

COS 126 Written Exam 2 (Spring 2015) COS 126 Written Exam 2 (Spring 2015) There are 8 questions on this exam, weighted as indicated below. This exam is closed book. You may use a single-page two-sided hand-written cheatsheet. There is a blank

More information

/ Download the Khateeb Classes App

/ Download the Khateeb Classes App Q) Write a program to read and display an array on screen. class Data public static void main(string args[ ]) throws IOException int i,n; InputStreamReader r = new InputStreamReader(System.in); BufferedReader

More information

Case Study: Savings Account Interest

Case Study: Savings Account Interest ecture 8 Loops: recap + example. Files: abstracting from a specific devise. Streams and Tokens. Examples. Material from the second half of Holmes Chapter 4. 1 w do you add up a sequence of numbers? = 1;

More information

Chapter 3. Selections

Chapter 3. Selections Chapter 3 Selections 1 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator 6. The Switch Statement 7. Useful Hints 2 1. Flow of

More information

Preview from Notesale.co.uk Page 9 of 108

Preview from Notesale.co.uk Page 9 of 108 The following list shows the reserved words in Java. These reserved words may not be used as constant or variable or any other identifier names. abstract assert boolean break byte case catch char class

More information

Recitation: Loop Jul 7, 2008

Recitation: Loop Jul 7, 2008 Nested Loop Recitation: Loop Jul 7, 2008 1. What is the output of the following program? Use pen and paper only. The output is: ****** ***** **** *** ** * 2. Test this program in your computer 3. Use "for

More information

ANSWER KEY First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010

ANSWER KEY First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010 ANSWER KEY First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010 1. True or False: (a) T An algorithm is a a set of directions for solving

More information