H212 Introduction to Software Systems Honors

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

Arrays, Part 3: Multidimensional arrays

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

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

Arrays Chapter 7. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Introduction to Arrays

COMP 202. Programming With Arrays

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

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

COMP 202. Programming With Arrays

Assignment 1 is due tonight at 11:59pm. Assignment 2 is due next Thursday at 11:59pm

2/2/18. Assignment 2 is due Wednesday 14 February at 11:59pm. Reading for Monday s lecture is the remainder of Chapter 7 and all of Chapter 8

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

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

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

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

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

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

Chapter 7: Arrays CS 121. April 9, Department of Computer Science College of Engineering Boise State University. Chapter 7: Arrays CS / 41

Object Oriented Programming. Java-Lecture 6 - Arrays

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

CS 112 Introduction to Programming

ECE 122. Engineering Problem Solving with Java

Spring 2010 Java Programming

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

ECE 122. Engineering Problem Solving with Java

CS111: PROGRAMMING LANGUAGE II

&KDSWHU$UUD\VDQG9HFWRUV

Oct Decision Structures cont d

Chapter 8 Arrays. Java Software Solutions. Foundations of Program Design Seventh Edition. John Lewis William Loftus

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

Arrays and File Input

Arrays and File Input

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

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

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

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

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

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

Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen)

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

Chapter 9 Introduction to Arrays. Fundamentals of Java

H212 Introduction to Software Systems Honors

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

Review: Array Initializer Lists

What two elements are usually present for calculating a total of a series of numbers?

CS111: PROGRAMMING LANGUAGE II

COE 212 Engineering Programming. Welcome to Exam I Tuesday November 11, 2014

CMPT 125: Lecture 4 Conditionals and Loops

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Computer Science is...

Arrays and the TOPICS CHAPTER 8. CONCEPT: An array can hold multiple values of the same data type simultaneously.

TOPICS TO COVER:-- Array declaration and use.

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

Programming with Java

( &% class MyClass { }

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

(A) 99 (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Chapter 8 Multi-Dimensional Arrays

CMPT 126: Lecture 6 Arrays

Example: Computing prime numbers

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

STUDENT LESSON A12 Iterations

Arrays. Eng. Mohammed Abdualal

Module 7: Arrays (Single Dimensional)

Happy Cinco de Mayo!!!!

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

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

Lab Assignment Three

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

Chapter 7: Arrays and the ArrayList Class

Faculty of Science Midterm. COMP-202B - Introduction to Computing I (Winter 2008)

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Last Class. More on loops break continue A bit on arrays

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

Last Class. While loops Infinite loops Loop counters Iterations

Happy Cinco de Mayo!!!!

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

COMP 202. Programming With Iterations. CONTENT: The WHILE, DO and FOR Statements. COMP Loops 1

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

Arrays Data structures Related data items of same type Remain same size once created Fixed-length entries

Array. Prepared By - Rifat Shahriyar

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

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

Arrays in Java Multi-dimensional Arrays

Fundamentals of Programming Data Types & Methods

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Building Java Programs

Java Classes: Random, Character A C S L E C T U R E 6

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

CSE 114 Computer Science I

Over and Over Again GEEN163

Transcription:

Introduction to Software Systems Honors Lecture #07: September 21, 2015 1/30

We explained last time that an array is an ordered list of values. Each value is stored at a specific, numbered position in the array. Array indexes always begin at zero. Array element: Element type: a value stored in an array the type of values that an array holds The element type can be a primitive type or an object reference We can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc. The entire array has a single name Each value has a numeric index 0 1 2 3 4 5 6 7 8 9 scores 79 87 94 82 67 98 87 81 74 91 2/30

An array element can be assigned a value, printed, or used in a calculation: scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println("Top = " + scores[5]); pick = scores[rand.nextint(11)]; Array element 3/30

In Java, the array itself is an object that must be instantiated Another way to depict the scores array: Array is an object scores 79 87 94 The name of the array is an object reference variable 82 67 98 87 81 74 91 4/30

Declaring arrays The scores array could be declared as follows: int[] scores = new int[10]; The type of the variable scores is int[] (an array of integers). Note that the array type does not specify its size, but each object of that type has a specific size. The reference variable scores is set to a new array object that can hold 10 integers. Other examples: int[] weights = new int[2000]; double[] prices = new double[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; 5/30

The number corresponding to each position is called an index or a subscript. Array indexes always begin at zero. In Java, arrays are objects. To create an array, the reference to the array must be declared. The array can then be instantiated using the new operator, which allocates memory space to store values. Once an array is declared to be a certain size, the number of values it can hold can NOT be changed. It is convenient to use for loops when handling arrays, because the number of positions in the array is constant. Example: Initializing an array and changing an array element 6/30

Example public class BasicArray // Creates an array, fills it with various integer values, // modifies one value, then prints them out. public static void main(string[] args) final int LIMIT = 15, MULTIPLE = 10; int[] list = new int[limit]; // Initialize the array values for (int index = 0; index < LIMIT; index++) list[index] = index * MULTIPLE; list[5] = 999; // change one array value // Print the array values, use iterator version of for for (int value : list) System.out.print(value + " "); Prints: 0 10 20 30 40 999 60 70 80 90 100 110 120 130 140 7/30

An index used in an array reference must specify a valid element. That is, the index value must be in range 0 to N-1. Bounds checking The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds. This is called automatic bounds checking. Each array object has a public constant called length that stores the size of the array. It is referenced using the array name: scores.length Note that length holds the number of elements, not the largest index. 8/30

Example: Reverse order import java.util.scanner; public class ReverseOrder // Reads a list of numbers from the user, // then prints them in the opposite order. public static void main(string[] args) Scanner scan = new Scanner(System.in); double[] numbers = new double[10]; System.out.println( Array size: " + numbers.length); for (int index = 0; index < numbers.length; index++) System.out.print("Enter number " + (index+1) + ": "); numbers[index] = scan.nextdouble(); System.out.println("The numbers in reverse order:"); for (int index = numbers.length-1; index >= 0; index--) System.out.print(numbers[index] + " "); 9/30

Example: Letter count import java.util.scanner; public class LetterCount // Reads a sentence from the user and counts the number of // uppercase and lowercase letters contained in it. public static void main(string[] args) final int NUMCHARS = 26; Scanner scan = new Scanner(System.in); int[] upper = new int[numchars]; int[] lower = new int[numchars]; char current; // the current character being processed int other = 0; // counter for non-alphabetics System.out.println("Enter a sentence:"); String line = scan.nextline(); // Count the number of each letter occurrence 10/30

Letter count for (int ch = 0; ch < line.length(); ch++) current = line.charat(ch); if (current >= 'A' && current <= 'Z') upper[current-'a']++; // A = 65, B = 66,.. else if (current >= 'a' && current <= 'z') lower[current-'a']++; else other++; // Print the results System.out.println(); for (int letter=0; letter < upper.length; letter++) System.out.print( (char) (letter + 'A') ); System.out.print(": " + upper[letter]); System.out.print("\t\t" + (char) (letter + 'a') ); System.out.println(": " + lower[letter]); System.out.println(); System.out.println("Non-alphabetic characters: " + other); 11/30

Letter count: example output 12/30

An initializer list can be used to instantiate and fill an array in one step. The values are delimited by braces and separated by commas Examples: Initializer lists int[] units = 147, 323, 89, 933, 540, 269, 97, 114, 298, 476; char[] grades = 'A', 'B', 'C', 'D', F'; Note that when an initializer list is used: the new operator is not used no size value is specified The size of the array is determined by the number of items in the list. An initializer list can be used only in the array declaration. 13/30

Prime numbers public class Primes //----------------------------------------------------------- // Stores some prime numbers in an array and prints them. //----------------------------------------------------------- public static void main(string[] args) int[] primenums = 2, 3, 5, 7, 11, 13, 17, 19; System.out.println("Array length: " + primenums.length); System.out.println("The first few prime numbers are:"); for (int prime : primenums) System.out.print(prime + " "); Output Array length: 8 The first few prime numbers are: 2 3 5 7 11 13 17 19 14/30

An entire array can be passed as a parameter to a method. as parameters Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other. Therefore, changing an array element within the method changes the original. An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type. 15/30

of objects The elements of an array can be object references. The following declaration reserves space to store 5 references to String objects: String[] words = new String[5]; It does NOT create the String objects themselves. Initially an array of objects holds null references. Each object stored in an array must be instantiated separately. The words array when initially declared: The words array after some String objects are created and stored in the array: words - - - - - words - - "friendship" "loyalty" "honor" 16/30

of objects String objects can be created using literals. The following declaration creates an array object called verbs and fills it with 5 String objects created using string literals: String[] verbs = "play", "work", "eat", "sleep", "run"; 17/30

Variable Length Parameter Lists Suppose we want to create a method that processes a different amount of data from one invocation to the next. For example, let's define a method called average that returns the average of a set of integer parameters: // one call to average three values mean1 = average(42, 69, 37); // another call to average seven values mean2 = average(35, 43, 93, 23, 40, 21, 75); Using special syntax in the formal parameter list, we can define a method to accept any number of parameters of the same type. For each call, the parameters are automatically put into an array for easy processing in the method: public double average(int... list) array name // whatever element Indicates a variable length type parameter list 18/30

Example: Variable number of parameters Calculating average for a variable number of input numbers. public double average(int... list) double result = 0.0; if (list.length!= 0) int sum = 0; for (int num : list) sum += num; result = (double)num / list.length; return result; 19/30

Exercise Write method called distance that accepts a variable number of integers (which each represent the distance of one leg of a trip) and returns the total distance of the trip. public int distance(int... list) int sum = 0; for (int num : list) sum = sum + num; return sum; 20/30

Variable Length Parameter Lists A method that accepts a variable number of parameters can also accept other parameters. The following method accepts an int, a String object, and a variable number of double values into an array called nums: public void test(int count, String name, double... nums) // whatever The varying number of parameters must come last in the formal arguments. A method cannot accept two sets of varying parameters. 21/30

A one-dimensional array stores a list of elements. Two-Dimensional A two-dimensional array can be thought of as a table of elements, with rows and columns. one dimension two dimensions In Java a two-dimensional array is an array of arrays. 22/30

Declaration of Two-Dimensional A two-dimensional array is declared by specifying the size of each dimension separately: int[][] table = new int[12][50]; An array element is referenced using two index values: value = table[3][6] The array stored in one row can be specified using one index. Expression Type Description table int[][] 2D array of integers, or array of integer arrays table[5] int[] array of integers table[5][12] int integer 23/30

public class TwoDArray // Creates a 2D array of integers, fills it with increasing // integer values, then prints them out. public static void main(string[] args) int[][] table = new int[5][10]; Example // Load the table with values for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) table[row][col] = row * 10 + col; // Print the table for (int row=0; row < table.length; row++) for (int col=0; col < table[row].length; col++) System.out.print(table[row][col] + "\t"); System.out.println(); 24/30

public class TwoDArray // Creates a 2D array of integers, fills it with increasing // integer values, then prints them out. public static void main(string[] args) int[][] table = new int[5][10]; Output Output: // Load the table with values for (int row=0; row < table.length; row++) 0 1 for (int 2 col=0; 3 col < table[row].length; 4 5 6 col++) 7 8 9 10 11 table[row][col] 12 13 = row 14 * 10 + 15col; 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 // Print 32 the table 33 34 35 36 37 38 39 40 41 for (int 42 row=0; row 43 < table.length; 44 45row++) 46 for (int col=0; col < table[row].length; col++) System.out.print(table[row][col] + "\t"); System.out.println(); 47 48 49 25/30

Example: Soda survey Suppose a soda manufacturer held a taste test for 4 new flavors to see how people liked them. The manufacturer got 10 people to try each new flavor and give it a score from 1 to 5. The 2-dimensional array called scores stores the results of that survey. Each row corresponds to a soda and each column in that row corresponds to the person who tasted it. The SodaSurvey program computes and prints the average responses for each soda and for each respondent. The sum of each soda and person are first stored in 1-dimensional arrays of integers. Ten the averages are computed and printed. As with 1-dimensional arrays, an initializer list can be used to instantiate a 2- dimensional array, where each element is itself an array initializer list. 26/30

Example: Soda survey import java.text.decimalformat; public class SodaSurvey // Determines and prints the average of each row (soda) and // each column (respondent) of the survey scores. public static void main(string[] args) int[][] scores = 3, 4, 5, 2, 1, 4, 3, 2, 4, 4, 2, 4, 3, 4, 3, 3, 2, 1, 2, 2, 3, 5, 4, 5, 5, 3, 2, 5, 5, 5, 1, 1, 1, 3, 1, 2, 1, 3, 2, 4 ; final int SODAS = scores.length; final int PEOPLE = scores[0].length; int[] sodasum = new int[sodas]; int[] personsum = new int[people]; 27/30

Example: Soda survey for (int soda=0; soda < SODAS; soda++) for (int person=0; person < PEOPLE; person++) sodasum[soda] += scores[soda][person]; personsum[person] += scores[soda][person]; DecimalFormat fmt = new DecimalFormat("0.#"); System.out.println("Averages:\n"); for (int soda=0; soda < SODAS; soda++) System.out.println("Soda #" + (soda+1) + ": " + fmt.format((float)sodasum[soda]/people)); System.out.println (); for (int person=0; person < PEOPLE; person++) System.out.println("Person #" + (person+1) + ": " + fmt.format((float)personsum[person]/sodas)); 28/30

Output Output: Averages: Soda #1: 3.2 Soda #2: 2.6 Soda #3: 4.2 Soda #4: 1.9 Person #1: 2.2 Person #2: 3.5 Person #3: 3.2 Person #4: 3.5 Person #5: 2.5 Person #6: 3 Person #7: 2 Person #8: 2.8 Person #9: 3.2 Person #10: 3.8 29/30

Multidimensional An array can have many dimensions if it has more than one dimension, it is called a multidimensional array. Each dimension subdivides the previous one into the specified number of elements. Each dimension has its own length constant. Because each dimension is an array of array references, the arrays within one dimension can be of different lengths. 30/30