Topics. Introduction to Arrays. Topics. Creating Arrays. Creating Arrays CS 146. Introduction to Programming and Algorithms Module 7

Size: px
Start display at page:

Download "Topics. Introduction to Arrays. Topics. Creating Arrays. Creating Arrays CS 146. Introduction to Programming and Algorithms Module 7"

Transcription

1 Introduction to Programming and Algorithms Module 7 CS 146 Sam Houston State University Dr. Tim McGuire Topics Module 7 discusses the following main topics: Introduction to Arrays Processing Array Contents Passing Arrays as Arguments Some Useful Array Algorithms and Operations Returning Arrays from Methods String Arrays Arrays of Objects The Sequential Search Algorithm 2 Topics Module 7 discusses the following main topics: The Selection Sort and Binary Search algorithms Two-Dimensional Arrays Arrays with Three or More Dimensions Command Line Arguments and Variable Length Argument Lists The Vector Class Introduction to Arrays Primitive variables are designed to hold only one value at a time. Arrays allow us to create a collection of like values that are indexed. An array can store any type of data but only one type of data at a time. An array is a list of data elements. 3 4 Creating Arrays An array is an object so it needs an object reference. int[] numbers; //declares a reference to an array that will hold integers. The next step, typically performed in the class constructor: numbers = new int[6]; //creates a new array that will hold 6 integers. index index 1 index 2 index 3 index 4 Array element values are initialized to. Array indexes always start at. index 5 Creating Arrays It is possible to declare an array reference and create it in the same statement. int[] numbers = new int[6]; Arrays may be of any type, not just int. float[] temperatures = new float[1]; char[] letters = new char[41]; long[] units = new long[5]; double[] sizes = new double[12]; 5 6 1

2 Creating Arrays The array size must be a non-negative number. It may be a literal value or be derived from a constant or variable. final int ARRAY_SIZE = 6; int[] numbers = new int[array_size]; Once created, an array size is fixed and cannot be changed. Accessing the Elements of an Array 2 numbers[] numbers[1] numbers[2] An array is accessed by: the reference name a subscript that identifies which element in the array to access. numbers[] = 2; //pronounced numbers sub zero numbers[3] numbers[4] numbers[5] 7 8 Inputing and Outputing Array Elements Array elements can be treated as any other variable. They are simply accessed by the same name and a subscript. Example: ArrayDemo1.java Array subscripts can be accessed using variables (such as for loop counters). Example: ArrayDemo2.java 9 Bounds Checking Array indexes always start at zero and continue to (array length - 1). int values = new int[1]; This array would have indexes through 9. Example: InvalidSubscript.java In for loops, it is typical to use i, j, and k as counting variables. It might help to think of i as representing the word index. 1 Off-by-1 Errors Array Initialization It is very easy to be off-by-one when accessing arrays. // This code has an off-by-one error. int[] numbers = new int[1]; for (int i = 1; i <= 1; i++) numbers[i] = 99; Here, the equal sign allows the loop to continue on to index 1, where 99 is the last index in the array. This code would throw an ArrayIndexOutOfBoundsException. Intitializing the data in an array could mean a lot of typing. int[] days = new int[12]; days[] = 31; // January days[1] = 28; // February

3 Array Initialization When relatively few items need to be initialized, an initialization list can be used to initialize the array. int[]days = 31, 28, 31, 3, 31, 3, 31, 31, 3, 31, 3, 31; The numbers in the list are stored in the array in order: days[] is assigned 31, days[1] is assigned 28, days[2] is assigned 31, days[3] is assigned 3, etc. Example: ArrayInitialization.java 13 Alternate Array Declaration Previously we showed arrays being declared: int[] numbers; However, the brackets can also go here: int numbers[]; These are equivalent but the first style is typical. Multiple arrays can be declared on the same line. int[] numbers, codes, scores; With the alternate notation each variable must have brackets. int numbers[], codes[], scores; The scores variable in this instance is simply an int variable. 14 Processing Array Contents Processing data in an array is the same as any other variable. grosspay = hours[3] * payrate; Pre and post increment works the same: int[] score = 7, 8, 9, 1, 11; ++score[2]; // Pre-increment operation score[4]++; // Post-increment operation Example: PayArray.java Processing Array Contents Array elements can be used in relational operations: if(cost[2] < cost[]) They can be used as loop conditions: while(value[count]!= ) Example: Overtime.java Array Size Arrays are objects and provide a length constant that can be tested. double[] temperatures = new double[25]; The length of this array is 25. The length of an array can be obtained via its length constant. int size = temperatures.length; The variable size will contain 25. Array Size The length constant can be used in a loop to provide automatic bounding. for(int i = ; i < temperatures.length; i++) System.out.println( Temperature + i : + temperatures[i]); // Be careful of off-by-one errors. It is possible to get the size of an array from a user: int size; int[] numbers; System.out.print("How many numbers do you have? "); size = Keyboard.readInt(); numbers = new int[size]; Example: DisplayTestScores.java

4 Reassigning Array References Reassigning Array References An array reference can be assigned to another array of the same type. // Create an array referenced by the numbers variable. int[] numbers = new int[1]; // Reassign numbers to a new array. numbers = new int[5]; If the first (ten element) array no longer has a reference to it, it will be garbage collected. The numbers variable holds the address of an int array. int[] numbers = new int[1]; 19 2 Reassigning Array References Copying Arrays The numbers variable holds the address of an int array. This array gets marked for garbage collection numbers = new int[5]; This is not the way to copy an array. int[] array1 = 2, 4, 6, 8, 1 ; int[] array2 = array1; // This does not copy array1. array1 holds an address to the array array2 holds an address to the array Example: SameArray.java Copying Arrays You cannot copy an array by merely assigning one reference variable to another. You need to copy the individual elements of one array to another. int[] firstarray = 5, 1, 15, 2, 25 ; int[] secondarray = new int[5]; for (int i = ; i < firstarray.length; i++) secondarray[i] = firstarray[i]; This code copies each element of firstarray to the corresponding element of Passing Array Elements as Arguments Array elements are handles like an independent variable. They are passed by value like any variable. showarray(numbers[]); Value Example: PassElements.java public static void showvalue(int element) System.out.print(element + " "); secondarray

5 Passing Arrays as Arguments Comparing Arrays Arrays are objects. Their references can be passed to methods like any other object reference variable. showarray(numbers); Example: PassArray.java public static void showarray(int[] array) for (int i = ; i < array.length; i++) System.out.print(array[i] + " "); 25 The == operator only compares if the array references point to the same array object. To compare the contents of an array: int[] firstarray = 2, 4, 6, 8, 1 ; int[] secondarray = 2, 4, 6, 8, 1 ; boolean arraysequal = true; int i = ; if (firstarray.length!= secondarray.length) arraysequal = false; while (arraysequal && i < firstarray.length) if (firstarray[i]!= secondarray[i]) arraysequal = false; i++; if (arraysequal) System.out.println("The arrays are equal."); else System.out.println("The arrays are not equal."); 26 Useful Array Operations Partially Filled Arrays Summing Array Elements: int total = ; // Initialize accumulator for (int i = ; i < units.length; i++) total += units[i]; Averaging Array Elements: double total = ; // Initialize accumulator double average; // Will hold the average for (int i = ; i < scores.length; i++) total += scores[i]; average = total / scores.length; Example: SalesData.java, Sales.java 27 Typically, if it is unknown how much data an array will be holding: size the array to the largest expected number of elements. use a counting variable to keep track of how much valid data is in the array. int[] array = new int[1]; int count = ; System.out.print("Enter a number or -1 to quit: "); number = Keyboard.readInt(); while (number!= -1 && count <= 99) count++; array[count - 1] = number; 28 Arrays and Files Arrays and Files Saving the contents of an array to a file: int[] numbers = 1, 2, 3, 4, 5; Reading the contents of a file into an array: int[] numbers = new int[5]; //assuming we know the size String str; int i = ; FileWriter fwriter = new FileWriter("Values.txt"); PrintWriter outputfile = new PrintWriter(fwriter); FileReader freader = new FileReader("Values.txt"); BufferedReader inputfile = new BufferedReader(freader); for (int i = ; i < numbers.length; i++) outputfile.println(numbers[i]); outputfile.close(); str = inputfile.readline(); while (str!= && i < numbers.length) numbers[i] = Integer.parseInt(str); i++; str = inputfile.readline(); inputfile.close();

6 Returning an Array Reference A method can return a reference to an array. The return type of the method must be declared as an array of the right type. public static double[] getarray() double[] array = 1.2, 2.3, 4.5, 6.7, 8.9 ; return array; The getarray method is a public static method that returns an array of doubles. Example: ReturnArray.java 31 String Arrays Arrays are not limited to primitive data. An array of String objects can be created: String[] names = "Bill", "Susan", "Steven", "Jean" ; The names variable holds the address to the array. names[] address names[1] address names[2] address names[3] address A String array is an array of references to String objects. Bill Susan Steven Jean Example: MonthDays.java 32 String Arrays If an initialization list is not provided, the new keyword must be used to create the array: String[] names = new String[4]; The names variable holds the address to the array. String Arrays When an array is created in this manner, each element of the array must be initialized. The names variable holds the address to the array. names[] = "Bill"; names[1] = "Susan"; names[2] = "Steven"; names[3] = "Jean"; names[] names[1] names[2] names[3] names[] names[1] names[2] names[3] Bill Susan Steven Jean Calling String Methods On Array Elements String objects have several methods. touppercase, tolowercase, compare, etc. Each element of a String array is a String object. Methods can be used by using the array name and index as before. System.out.println(names[].toUpperCase()); Example: StringArrayMethods.java The length Field & The length method Arrays have a final field named length. String objects have a method named length. To display the length of each string held in a String array: for (int i = ; i < names.length; i++) System.out.println(names[i].length()); An array s length member is a field You do not write a set of parentheses after its name. You do write the parentheses after the name of the String class s length method

7 Arrays of Objects Arrays of Objects Since Strings are objects, we know that arrays can contain objects. InventoryItem[] inventory = new InventoryItem[5]; The inventory variable holds the address of an InventoryItem array. Each element needs to be initialized. for (int i = ; i < inventory.length; i++) inventory[i] = new InventoryItem(); Example: ObjectArray.java The inventory variable holds the address of an InventoryItem array. units: units: inventory[] inventory[1] inventory[2] inventory[3] inventory[4] 37 inventory[] inventory[1] inventory[2] inventory[3] inventory[4] units: units: units: 38 Sorting an Array Using Array.Sort() Java provides a class named Array that simplifies some array operations. The Array class has a static method named sort that will sort a numeric array in ascending order. Array.sort(numbers); To use the class, the import statement, import java.util.array; must be used. Example: SortDemo.java The Sequential Search Algorithm A search algorithm is a method of locating a specific item in a larger collection of data. The sequential search algorithm uses a loop to: sequentially step through an array, comparing each element with the search value, and stopping when the value is found or the end of the array is encountered. Example: SearchArray.java, TestSearch.java 39 4 The Selection Sort Algorithm A sort algorithm is a method of arranging data in a chosen order The Selection Sort algorithm uses a nested loops to: sequentially step through an array multiple times, comparing elements to a chosen minimum value and swapping when Smaller value is found Selection Sort Pseudocode For startscan is each subscript in array from through the next-to-last subscript Set index variable to startscan. Set minindex variable to startscan. Set minvalue variable to array[startscan]. For index is each subscript in array from (startscan + 1) through the next-to-last subscript If array[index] is less than minvalue Set minvalue to array[index]. Set minindex to index. End If. Increment index. End For. Set array[minindex] to array[startscan]. Set array[startscan] to minvalue. End For. Example: SelectionSortDemo.java

8 Selection Sort Method public static void selectionsort(int[] array) int startscan, index, minindex, minvalue; for (startscan = ; startscan < (array.length-1); startscan++) minindex = startscan; minvalue = array[startscan]; for(index = startscan + 1; index < array.length; index++) if (array[index] < minvalue) minvalue = array[index]; minindex = index; array[minindex] = array[startscan]; array[startscan] = minvalue; 43 The Binary Search Algorithm Binary search is far more efficient that sequential search, especially for large data collections Often referred to as Divide and Conquer The Binary Search algorithm uses a loop to: Select the middle array element, Compare the search value to the value found End if values match Eliminate top half of array if search value < middle Eliminate bottom half of array if search value > middle Example: BinarySearchDemo.java 44 Binary Search Pseudocode Set first to. Set last to the last subscript in the array. Set found to false. Set position to -1. While found is not true and first is less than or equal to last Set middle to the subscript half-way between array[first]and array[last]. If array[middle] equals the desired value Set found to true. Set position to middle. Else If array[middle] is greater than the desired value Set last to middle - 1. Else Set first to middle + 1. End If. End While. Return position. 45 Binary Search Method public static int binarysearch(int[] array, int value) int first, last; // First and Last array elements int middle, position; // Middle position & position of search value boolean found; // Flag // Set the inital values. first = ; last = array.length - 1; position = -1; found = false; // Search for the value. while (!found && first <= last) middle = (first + last) / 2; // Calculate mid point if (array[middle] == value) // If value is found at mid found = true; position = middle; else if (array[middle] > value) // If value is in lower half last = middle - 1; else first = middle + 1; // If value is in upper half // Return the position of the item, or -1 // if it was not found. return position; 46 Parallel Arrays By using the same subscript, you can build relationships between data stored in two or more arrays. String[] names = new String[5]; String[] addresses = new String[5]; The names array stores the names of five persons The addresses array stores the addresses of the same five persons. The data for one person is stored at the same index in each array. 47 names[] Person #1 Parallel Arrays Relationship between names and addresses array elements. names[1] Person #2 names[2] Person #3 names[3] Person #4 names[4] Person #5 addresses[] addresses[1] addresses[2] addresses[3] addresses[4] Parallel arrays are useful when storing data of unlike types. Example: ParallelArrays.java 48 8

9 Command-Line Arguments A Java program can receive arguments from the operating system command-line. The main method with a header that looks like this: public static void main(string[] args) The main method receives a String array as a parameter. The array that is passed into the args parameter comes from the operating system command-line. Example: CommandLine.java Command-Line Arguments To run the example: java CommandLine How does this work? args[] is assigned How args[] is assigned does args[] is assigned this args[] is assigned work? It is not required that the name of main s parameter array be args The Random Class Some applications, such as games and simulations, require the use of randomly generated numbers. The Java API has a class, Random, for this purpose. The Random class uses an algorithm to generate a sequence of random numbers. 51 9

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION 1. Write a loop that computes (No need to write a complete program) 100 1 99 2 98 3 97... 4 3 98 2 99 1 100 Note: this is not the only solution; double sum

More information

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

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O 1 Sending Output to a (Text) File import java.util.scanner; import java.io.*; public class TextFileOutputDemo1 public static void

More information

In this Chapter you ll learn:

In this Chapter you ll learn: Now go, write it before them in a table, and note it in a book. Isaiah 30:8 To go beyond is as wrong as to fall short. Confucius Begin at the beginning, and go on till you come to the end: then stop. Lewis

More information

Iteration CHAPTER 6. Topic Summary

Iteration CHAPTER 6. Topic Summary CHAPTER 6 Iteration TOPIC OUTLINE 6.1 while Loops 6.2 for Loops 6.3 Nested Loops 6.4 Off-by-1 Errors 6.5 Random Numbers and Simulations 6.6 Loop Invariants (AB only) Topic Summary 6.1 while Loops Many

More information

Introduction to Java

Introduction to Java Introduction to Java The HelloWorld program Primitive data types Assignment and arithmetic operations User input Conditional statements Looping Arrays CSA0011 Matthew Xuereb 2008 1 Java Overview A high

More information

Computer Programming I

Computer Programming I Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,

More information

Moving from CS 61A Scheme to CS 61B Java

Moving from CS 61A Scheme to CS 61B Java Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you

More information

Object-Oriented Programming in Java

Object-Oriented Programming in Java CSCI/CMPE 3326 Object-Oriented Programming in Java Class, object, member field and method, final constant, format specifier, file I/O Dongchul Kim Department of Computer Science University of Texas Rio

More information

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 Oct 4, 2013, p 1 Name: CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013 1. (max 18) 4. (max 16) 2. (max 12) 5. (max 12) 3. (max 24) 6. (max 18) Total: (max 100)

More information

Arrays in Java. Working with Arrays

Arrays in Java. Working with Arrays Arrays in Java So far we have talked about variables as a storage location for a single value of a particular data type. We can also define a variable in such a way that it can store multiple values. Such

More information

Arrays. Introduction. Chapter 7

Arrays. Introduction. Chapter 7 CH07 p375-436 1/30/07 1:02 PM Page 375 Chapter 7 Arrays Introduction The sequential nature of files severely limits the number of interesting things you can easily do with them.the algorithms we have examined

More information

Zabin Visram Room CS115 CS126 Searching. Binary Search

Zabin Visram Room CS115 CS126 Searching. Binary Search Zabin Visram Room CS115 CS126 Searching Binary Search Binary Search Sequential search is not efficient for large lists as it searches half the list, on average Another search algorithm Binary search Very

More information

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing Multi-dimensional Arrays The elements of an array can be any type Including an array type So int 2D[] []; declares an array of arrays of int Two dimensional arrays are useful for representing tables of

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Object Oriented Software Design

Object Oriented Software Design Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction

More information

Introduction to Programming System Design. CSCI 455x (4 Units)

Introduction to Programming System Design. CSCI 455x (4 Units) Introduction to Programming System Design CSCI 455x (4 Units) Description This course covers programming in Java and C++. Topics include review of basic programming concepts such as control structures,

More information

VB.NET Programming Fundamentals

VB.NET Programming Fundamentals Chapter 3 Objectives Programming Fundamentals In this chapter, you will: Learn about the programming language Write a module definition Use variables and data types Compute with Write decision-making statements

More information

Pseudo code Tutorial and Exercises Teacher s Version

Pseudo code Tutorial and Exercises Teacher s Version Pseudo code Tutorial and Exercises Teacher s Version Pseudo-code is an informal way to express the design of a computer program or an algorithm in 1.45. The aim is to get the idea quickly and also easy

More information

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand: Introduction to Programming and Algorithms Module 2 CS 146 Sam Houston State University Dr. Tim McGuire Introduction To Computers And Java Chapter Objectives To understand: the meaning and placement of

More information

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below: http://www.tutorialspoint.com/java/java_methods.htm JAVA - METHODS Copyright tutorialspoint.com A Java method is a collection of statements that are grouped together to perform an operation. When you call

More information

Chapter 2: Elements of Java

Chapter 2: Elements of Java Chapter 2: Elements of Java Basic components of a Java program Primitive data types Arithmetic expressions Type casting. The String type (introduction) Basic I/O statements Importing packages. 1 Introduction

More information

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays. Arrays Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html 1 Grid in Assignment 2 How do you represent the state

More information

Crash Course in Java

Crash Course in Java Crash Course in Java Based on notes from D. Hollinger Based in part on notes from J.J. Johns also: Java in a Nutshell Java Network Programming and Distributed Computing Netprog 2002 Java Intro 1 What is

More information

Programming Languages CIS 443

Programming Languages CIS 443 Course Objectives Programming Languages CIS 443 0.1 Lexical analysis Syntax Semantics Functional programming Variable lifetime and scoping Parameter passing Object-oriented programming Continuations Exception

More information

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following: In creating objects of the type, we have used statements similar to the following: f = new (); The parentheses in the expression () makes it look like a method, yet we never created such a method in our

More information

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasket { public static void main(string[]

More information

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C Basic Java Constructs and Data Types Nuts and Bolts Looking into Specific Differences and Enhancements in Java compared to C 1 Contents Hello World Program Statements Explained Java Program Structure in

More information

Java Basics: Data Types, Variables, and Loops

Java Basics: Data Types, Variables, and Loops Java Basics: Data Types, Variables, and Loops If debugging is the process of removing software bugs, then programming must be the process of putting them in. - Edsger Dijkstra Plan for the Day Variables

More information

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas CS 110B - Rule Storage Classes Page 18-1 Attributes are distinctive features of a variable. Data type, int or double for example, is an attribute. Storage class is another attribute. There are four storage

More information

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT BSc (Hons) in Computer Applications, BSc (Hons) Computer Science with Network Security, BSc (Hons) Business Information Systems & BSc (Hons) Software Engineering Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT

More information

Java Interview Questions and Answers

Java Interview Questions and Answers 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write and compile the java

More information

AP Computer Science Java Mr. Clausen Program 9A, 9B

AP Computer Science Java Mr. Clausen Program 9A, 9B AP Computer Science Java Mr. Clausen Program 9A, 9B PROGRAM 9A I m_sort_of_searching (20 points now, 60 points when all parts are finished) The purpose of this project is to set up a program that will

More information

8.1. Example: Visualizing Data

8.1. Example: Visualizing Data Chapter 8. Arrays and Files In the preceding chapters, we have used variables to store single values of a given type. It is sometimes convenient to store multiple values of a given type in a single collection

More information

J a v a Quiz (Unit 3, Test 0 Practice)

J a v a Quiz (Unit 3, Test 0 Practice) Computer Science S-111a: Intensive Introduction to Computer Science Using Java Handout #11 Your Name Teaching Fellow J a v a Quiz (Unit 3, Test 0 Practice) Multiple-choice questions are worth 2 points

More information

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java

More information

Part I. Multiple Choice Questions (2 points each):

Part I. Multiple Choice Questions (2 points each): Part I. Multiple Choice Questions (2 points each): 1. Which of the following is NOT a key component of object oriented programming? (a) Inheritance (b) Encapsulation (c) Polymorphism (d) Parallelism ******

More information

AP Computer Science Java Subset

AP Computer Science Java Subset APPENDIX A AP Computer Science Java Subset The AP Java subset is intended to outline the features of Java that may appear on the AP Computer Science A Exam. The AP Java subset is NOT intended as an overall

More information

Curriculum Map. Discipline: Computer Science Course: C++

Curriculum Map. Discipline: Computer Science Course: C++ Curriculum Map Discipline: Computer Science Course: C++ August/September: How can computer programs make problem solving easier and more efficient? In what order does a computer execute the lines of code

More information

CS 111 Classes I 1. Software Organization View to this point:

CS 111 Classes I 1. Software Organization View to this point: CS 111 Classes I 1 Software Organization View to this point: Data Objects and primitive types Primitive types operators (+, /,,*, %). int, float, double, char, boolean Memory location holds the data Objects

More information

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program. Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

More information

The C Programming Language course syllabus associate level

The C Programming Language course syllabus associate level TECHNOLOGIES The C Programming Language course syllabus associate level Course description The course fully covers the basics of programming in the C programming language and demonstrates fundamental programming

More information

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game Directions: In mobile Applications the Control Model View model works to divide the work within an application.

More information

Class : MAC 286. Data Structure. Research Paper on Sorting Algorithms

Class : MAC 286. Data Structure. Research Paper on Sorting Algorithms Name : Jariya Phongsai Class : MAC 286. Data Structure Research Paper on Sorting Algorithms Prof. Lawrence Muller Date : October 26, 2009 Introduction In computer science, a ing algorithm is an efficient

More information

Statements and Control Flow

Statements and Control Flow Contents 1. Introduction 2. Types and Variables 3. Statements and Control Flow 4. Reading Input 5. Classes and Objects 6. Arrays 7. Methods 8. Scope and Lifetime 9. Utility classes 10. Introduction to

More information

LOOPS CHAPTER CHAPTER GOALS

LOOPS CHAPTER CHAPTER GOALS jfe_ch04_7.fm Page 139 Friday, May 8, 2009 2:45 PM LOOPS CHAPTER 4 CHAPTER GOALS To learn about while, for, and do loops To become familiar with common loop algorithms To understand nested loops To implement

More information

Java Programming Fundamentals

Java Programming Fundamentals Lecture 1 Part I Java Programming Fundamentals Topics in Quantitative Finance: Numerical Solutions of Partial Differential Equations Instructor: Iraj Kani Introduction to Java We start by making a few

More information

public static void main(string[] args) { System.out.println("hello, world"); } }

public static void main(string[] args) { System.out.println(hello, world); } } Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static

More information

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A Developed By Brian Weinfeld Course Description: AP Computer

More information

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class

Problem 1. CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class CS 61b Summer 2005 Homework #2 Due July 5th at the beginning of class This homework is to be done individually. You may, of course, ask your fellow classmates for help if you have trouble editing files,

More information

WRITING DATA TO A BINARY FILE

WRITING DATA TO A BINARY FILE WRITING DATA TO A BINARY FILE TEXT FILES VS. BINARY FILES Up to now, we have looked at how to write and read characters to and from a text file. Text files are files that contain sequences of characters.

More information

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science

First Java Programs. V. Paúl Pauca. CSC 111D Fall, 2015. Department of Computer Science Wake Forest University. Introduction to Computer Science First Java Programs V. Paúl Pauca Department of Computer Science Wake Forest University CSC 111D Fall, 2015 Hello World revisited / 8/23/15 The f i r s t o b l i g a t o r y Java program @author Paul Pauca

More information

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4 NOTE: SUN ONE Studio is almost identical with NetBeans. NetBeans is open source and can be downloaded from www.netbeans.org. I

More information

Answers to Review Questions Chapter 7

Answers to Review Questions Chapter 7 Answers to Review Questions Chapter 7 1. The size declarator is used in a definition of an array to indicate the number of elements the array will have. A subscript is used to access a specific element

More information

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation

Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science updated 03/08/2012 Unit 1: JKarel 8 weeks http://www.fcps.edu/is/pos/documents/hs/compsci.htm

More information

Chulalongkorn University International School of Engineering Department of Computer Engineering 2140105 Computer Programming Lab.

Chulalongkorn University International School of Engineering Department of Computer Engineering 2140105 Computer Programming Lab. Chulalongkorn University Name International School of Engineering Student ID Department of Computer Engineering Station No. 2140105 Computer Programming Lab. Date Lab 2 Using Java API documents, command

More information

Chapter 2 Introduction to Java programming

Chapter 2 Introduction to Java programming Chapter 2 Introduction to Java programming 1 Keywords boolean if interface class true char else package volatile false byte final switch while throws float private case return native void protected break

More information

Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

More information

Example of a Java program

Example of a Java program Example of a Java program class SomeNumbers static int square (int x) return x*x; public static void main (String[] args) int n=20; if (args.length > 0) // change default n = Integer.parseInt(args[0]);

More information

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1 QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For

More information

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Handout 1 CS603 Object-Oriented Programming Fall 15 Page 1 of 11 Handout 1 Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner. Java

More information

INPUT AND OUTPUT STREAMS

INPUT AND OUTPUT STREAMS INPUT AND OUTPUT The Java Platform supports different kinds of information sources and information sinks. A program may get data from an information source which may be a file on disk, a network connection,

More information

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10) File class in Java File Input and Output (Savitch, Chapter 10) TOPICS File Input Exception Handling File Output Programmers refer to input/output as "I/O". The File class represents files as objects. The

More information

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be: Lecture 7 Picking Balls From an Urn The problem: An urn has n (n = 10) balls numbered from 0 to 9 A ball is selected at random, its' is number noted, it is set aside, and another ball is selected from

More information

One Dimension Array: Declaring a fixed-array, if array-name is the name of an array

One Dimension Array: Declaring a fixed-array, if array-name is the name of an array Arrays in Visual Basic 6 An array is a collection of simple variables of the same type to which the computer can efficiently assign a list of values. Array variables have the same kinds of names as simple

More information

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London

More information

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system. http://www.tutorialspoint.com/java/java_quick_guide.htm JAVA - QUICK GUIDE Copyright tutorialspoint.com What is Java? Java is: Object Oriented Platform independent: Simple Secure Architectural- neutral

More information

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays Motivation Suppose that we want a program that can read in a list of numbers and sort that list, or nd the largest value in that list. To be concrete about it, suppose we have 15 numbers to read in from

More information

Why? A central concept in Computer Science. Algorithms are ubiquitous.

Why? A central concept in Computer Science. Algorithms are ubiquitous. Analysis of Algorithms: A Brief Introduction Why? A central concept in Computer Science. Algorithms are ubiquitous. Using the Internet (sending email, transferring files, use of search engines, online

More information

Moving from C++ to VBA

Moving from C++ to VBA Introduction College of Engineering and Computer Science Mechanical Engineering Department Mechanical Engineering 309 Numerical Analysis of Engineering Systems Fall 2014 Number: 15237 Instructor: Larry

More information

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming 1 2 Foreword First of all, this book isn t really for dummies. I wrote it for myself and other kids who are on the team. Everything

More information

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner java.util.scanner java.util.scanner is a class in the Java API used to create a Scanner object, an extremely versatile object that you can use to input alphanumeric characters from several input sources

More information

The following program is aiming to extract from a simple text file an analysis of the content such as:

The following program is aiming to extract from a simple text file an analysis of the content such as: Text Analyser Aim The following program is aiming to extract from a simple text file an analysis of the content such as: Number of printable characters Number of white spaces Number of vowels Number of

More information

Goals for This Lecture:

Goals for This Lecture: Goals for This Lecture: Understand the pass-by-value and passby-reference argument passing mechanisms of C++ Understand the use of C++ arrays Understand how arrays are passed to C++ functions Call-by-value

More information

Unit 6. Loop statements

Unit 6. Loop statements Unit 6 Loop statements Summary Repetition of statements The while statement Input loop Loop schemes The for statement The do statement Nested loops Flow control statements 6.1 Statements in Java Till now

More information

Java Cheatsheet. http://introcs.cs.princeton.edu/java/11cheatsheet/ Tim Coppieters Laure Philips Elisa Gonzalez Boix

Java Cheatsheet. http://introcs.cs.princeton.edu/java/11cheatsheet/ Tim Coppieters Laure Philips Elisa Gonzalez Boix Java Cheatsheet http://introcs.cs.princeton.edu/java/11cheatsheet/ Tim Coppieters Laure Philips Elisa Gonzalez Boix Hello World bestand genaamd HelloWorld.java naam klasse main methode public class HelloWorld

More information

Java Application Developer Certificate Program Competencies

Java Application Developer Certificate Program Competencies Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle

More information

Chapter 1 Java Program Design and Development

Chapter 1 Java Program Design and Development presentation slides for JAVA, JAVA, JAVA Object-Oriented Problem Solving Third Edition Ralph Morelli Ralph Walde Trinity College Hartford, CT published by Prentice Hall Java, Java, Java Object Oriented

More information

Pemrograman Dasar. Basic Elements Of Java

Pemrograman Dasar. Basic Elements Of Java Pemrograman Dasar Basic Elements Of Java Compiling and Running a Java Application 2 Portable Java Application 3 Java Platform Platform: hardware or software environment in which a program runs. Oracle

More information

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007 The Java Type System By now, you have seen a fair amount of Java. Time to study in more depth the foundations of the language,

More information

Introduction to Data Structures

Introduction to Data Structures Introduction to Data Structures Albert Gural October 28, 2011 1 Introduction When trying to convert from an algorithm to the actual code, one important aspect to consider is how to store and manipulate

More information

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013 Masters programmes in Computer Science and Information Systems Object-Oriented Design and Programming Sample module entry test xxth December 2013 This sample paper has more questions than the real paper

More information

Symbol Tables. Introduction

Symbol Tables. Introduction Symbol Tables Introduction A compiler needs to collect and use information about the names appearing in the source program. This information is entered into a data structure called a symbol table. The

More information

RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE. CISY 105 Foundations of Computer Science

RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE. CISY 105 Foundations of Computer Science I. Basic Course Information RARITAN VALLEY COMMUNITY COLLEGE ACADEMIC COURSE OUTLINE CISY 105 Foundations of Computer Science A. Course Number and Title: CISY-105, Foundations of Computer Science B. New

More information

Building a Multi-Threaded Web Server

Building a Multi-Threaded Web Server Building a Multi-Threaded Web Server In this lab we will develop a Web server in two steps. In the end, you will have built a multi-threaded Web server that is capable of processing multiple simultaneous

More information

1. Writing Simple Classes:

1. Writing Simple Classes: The University of Melbourne Department of Computer Science and Software Engineering 433-254 Software Design Semester 2, 2003 Answers for Lab 2 Week 3 1. Writing Simple Classes: a) In Java systems, there

More information

Computer Programming I

Computer Programming I Computer Programming I Levels: 10-12 Units of Credit: 1.0 CIP Code: 11.0201 Core Code: 35-02-00-00-030 Prerequisites: Secondary Math I, Keyboarding Proficiency, Computer Literacy requirement (e.g. Exploring

More information

Java from a C perspective. Plan

Java from a C perspective. Plan Java from a C perspective Cristian Bogdan 2D2052/ingint04 Plan Objectives and Book Packages and Classes Types and memory allocation Syntax and C-like Statements Object Orientation (minimal intro) Exceptions,

More information

Event-Driven Programming

Event-Driven Programming Event-Driven Programming Lecture 4 Jenny Walter Fall 2008 Simple Graphics Program import acm.graphics.*; import java.awt.*; import acm.program.*; public class Circle extends GraphicsProgram { public void

More information

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language Translation Translating to Java Introduction to Computer Programming The job of a programmer is to translate a problem description into a computer language. You need to be able to convert a problem description

More information

Introduction to Stacks

Introduction to Stacks Introduction to Stacks What is a Stack Stack implementation using array. Stack implementation using linked list. Applications of Stack. What is a Stack? Stack is a data structure in which data is added

More information

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program. Software Testing Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program. Testing can only reveal the presence of errors and not the

More information

6. Standard Algorithms

6. Standard Algorithms 6. Standard Algorithms The algorithms we will examine perform Searching and Sorting. 6.1 Searching Algorithms Two algorithms will be studied. These are: 6.1.1. inear Search The inear Search The Binary

More information

Conditional Statements. 15-110 Summer 2010 Margaret Reid-Miller

Conditional Statements. 15-110 Summer 2010 Margaret Reid-Miller Conditional Statements 15-110 Summer 2010 Margaret Reid-Miller Conditional statements Within a method, we can alter the flow of control (the order in which statements are executed) using either conditionals

More information

Introduction to Java. CS 3: Computer Programming in Java

Introduction to Java. CS 3: Computer Programming in Java Introduction to Java CS 3: Computer Programming in Java Objectives Begin with primitive data types Create a main class with helper methods Learn how to call built-in class methods and instance methods

More information

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I CS 106 Introduction to Computer Science I 01 / 21 / 2014 Instructor: Michael Eckmann Today s Topics Introduction Homework assignment Review the syllabus Review the policies on academic dishonesty and improper

More information

An Incomplete C++ Primer. University of Wyoming MA 5310

An Incomplete C++ Primer. University of Wyoming MA 5310 An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages

More information

Searching Algorithms

Searching Algorithms Searching Algorithms The Search Problem Problem Statement: Given a set of data e.g., int [] arr = {10, 2, 7, 9, 7, 4}; and a particular value, e.g., int val = 7; Find the first index of the value in the

More information

java Features Version April 19, 2013 by Thorsten Kracht

java Features Version April 19, 2013 by Thorsten Kracht java Features Version April 19, 2013 by Thorsten Kracht Contents 1 Introduction 2 1.1 Hello World................................................ 2 2 Variables, Types 3 3 Input/Output 4 3.1 Standard I/O................................................

More information

CmpSci 187: Programming with Data Structures Spring 2015

CmpSci 187: Programming with Data Structures Spring 2015 CmpSci 187: Programming with Data Structures Spring 2015 Lecture #12 John Ridgway March 10, 2015 1 Implementations of Queues 1.1 Linked Queues A Linked Queue Implementing a queue with a linked list is

More information