How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

Arrays An array is a structure that holds multiple values of the same type. The length of an array is established when the array is created (at runtime).
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays –Data structures which reference one or more value –All items must have same data.
Introduction to Computers and Programming Lecture 15: Arrays Professor: Evan Korth New York University.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 7 - Arrays Outline 7.1 Introduction 7.2 Arrays 7.3 Declaring and Creating Arrays 7.4 Examples Using.
ECE122 L13: Arrays of Objects March 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 13 Arrays of Objects.
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Arrays Chapter 7. 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
BUILDING JAVA PROGRAMS CHAPTER 7 Arrays. Exam #2: Chapters 1-6 Thursday Dec. 4th.
Introduction to Collections Arrays. Collections Collections allow us to treat a group of values as one collective entity. The array is a collection of.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
1 Array basics. Data Structures Sometimes, we have data that have some natural structure to them  A few examples: Texts are sequences of characters Images.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Arrays.
Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 Khalid Siddiqui.
int [] scores = new int [10];
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
Grouping Data Together Often we want to group together a number of values or objects to be treated in the same way e.g. names of students in a tutorial.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
 2005 Pearson Education, Inc. All rights reserved Arrays.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Introduction to programming in java Lecture 21 Arrays – Part 1.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Array in C# Array in C# RIHS Arshad Khan
Arrays Chapter 7.
Arrays, 2-D Arrays, and ArrayList
Building Java Programs
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
int [] scores = new int [10];
Arrays .
Cs212: Data Structures Computer Science Department Lecture 2: Arrays.
Arrays ICS2O.
Arrays Chapter 7.
int [] scores = new int [10];
Announcements Lab 6 was due today Lab 7 assigned this Friday
Building Java Programs
Arrays in Java.
Building Java Programs
Suggested self-checks: Section 7.11 #1-11
CS1001 Lecture 14.
Building Java Programs
Dry Run Fix it Write a program
How do you do the following?
Presentation transcript:

How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include the following Vocabulary Ideas Examples Questions

Java: Arrays 10/19/2015

Objectives: Understand arrays and when to use them. Understand the vocabulary and syntax associated with using arrays. Be able to program using an array of primitives.

When to use Arrays Large group of similar information. Use the information more than once. Sorting Tallying, i.e. elections

What is an Array An array is a block of consecutive memory locations that hold values of the same data type. Individual locations are called array’s elements. When we say “element” we often mean the value stored in that element An array of doubles

What is an Array (cont’d) Rather than treating each element as a separate named variable, the whole array gets one name. Specific array elements are referred to by using array’s name and the element’s number, called index or subscript. c[0]c[1]c[2]c[3] c is array’s name

When to use an array When you are temporarily storing a large group of similar information When you need to use the information more than once When sorting.

Indices, Subscripts, addresses In Java, an index is written within square brackets following array’s name (for example, a[k]). Indices start from 0; the first element of an array a is referred to as a[0] and the n-th element as a[n - 1]. An index can have any int value from 0 to array’s length - 1.

Indices (cont’d) We can use as an index an int variable or any expression that evaluates to an int value. For example: a [3] a [k] a [k - 2] a [ (int) (6*Math.random()) ]

Indices (cont’d) In Java, an array is declared with fixed length that cannot be changed. Java interpreter checks the values of indices at run time and throws ArrayIndexOutOfBoundsException if an index is negative or if it is greater than the (length of the array – 1).

Why Do We Need Arrays? The power of arrays comes from the fact that the value of a subscript can be computed and updated at run time. int sum = 0; sum += score0; sum += score1; … sum += score999; No arrays: int n = 1000; int sum = 0, k; for (k = 0; k < n; k++) sum += scores[k]; With arrays: 1000 times!

Why Arrays? (cont’d) Arrays give direct access (random access) to any element — no need to scan the array. if (k == 0) System.out.print (score0); else if (k == 1) System.out.print (score1); else … // etc. System.out.print (scores[k]); 1000 times! No arrays: With arrays:

Vocab. Check. Array Index Element Primitive Subscript ArrayIndexOutOfBoundsException

Arrays as Objects In Java, an array is an object. If the type of its elements is anyType, the type of the array object is anyType[ ]. Array declaration: anyType [ ] arrName; What is arrName?

Arrays as Objects (cont’d) As with other objects, the declaration creates only a reference, initially set to null. An array must be created before it can be used. One way to create an array: arrName = new anyType [length] ; Brackets, not parens! anyType [ ] arrName; int [] numbers; numbers = new int [100];

When an array is created, space is allocated to hold its elements. If a list of values is not given, the elements get the default values. For example: Declaration and Initialization int [] scores; scores = new int [10] ; String [] words; words = new String [10000]; length 10, all values set to 0 length 10000, all values set to null

Initialization (cont’d) An array can be declared and initialized in one statement. For example: int [ ] scores = new int [10] ; double [ ] gasPrices = { 3.05, 3.17, 3.59 }; String [ ] words = new String [10000]; String [ ] cities = {"Atlanta", "Boston", "Cincinnati" }; The left side creates the pointer, reference, object The right side creates what is being pointed to, referred to, …

String [ ] words;... words = new String [ input.nextInt() ]; double[ ] gasPrices; … gasPrices = new double[ ] { 3.05, 3.17, 3.59 }; Initialization (cont’d) Otherwise, initialization can be postponed until later. For example: Not yet initialized

Review An array.. –Holds a large group of similar information –When you need to use the information more than once –When you are sorting What are some pros and cons of arrays?

Your turn to declare Declare arrays to store the following The names of 15 people The gpas for each person The scores of 10, 15, -8, and 14

Array’s Length The length of an array is determined when that array is created. The length is either given explicitly or comes from the length of the {…} initialization list. The length of an array arrName is referred to in the code as arrName.length. length is a public field (not a method) in an array object. That is why it is not arrName.length().

Initializing Elements Unless specific values are given in a {…} list, all the elements are initialized to the default value: 0 for numbers, false for booleans, null for objects. If its elements are objects, the array holds references to objects, which are initially set to null. Each object-type element must be initialized before it is used.

What do you recall about… Arrays Index Address ArrayIndexOutOfBoundsException Can the size of an array change? What does this line of code do? –double [ ] gpas = new double [15]; How can you find the number of elements in an array?

Your turn, in BlueJ Declare arrays to hold the following –Ten ages –The names: Mannie, Moe, Jack and Curly –5 Radio stations In BlueJ, Write the code to input values into the ages array. Write the code to display the information from the ages array

What do these line of code do? double [ ] gasPrices = { 3.05, 3.17, 3.59 }; for (int i=0; i<gasPrices.length;i++) System.out.print(gasPrices[i]+ " "); System.out.println(); gasPrices = new double[ ] { 1, 5.9 }; for (int i=0; i<gasPrices.length;i++) System.out.print(gasPrices[i]+ " "); System.out.println(); gasPrices = new double[ ] { 4.0, 3.64, 2, 12}; for (int i=0; i<gasPrices.length;i++) System.out.print(gasPrices[i]+" "); System.out.println();

How can you… Create an integer array called scores that will hold 10 scores? –int [] scores = new int[10]; What is the code to get the scores from the user?

How can you … Find the average of the array declared previously?

Sample Array Code public class ArrayDemo { public static void main(String[] args) { int [] anArray; // declare an array of integers anArray = new int[10]; // create the array // assign a value to each array element and print for (int i = 0; i < anArray.length; i++) { anArray[i] = i; System.out.print(anArray[i] + " "); } System.out.println(); } Can also int [] anArray = new int[10]; To both declare and create. Notice the addresses go from 0 to 9, anArray.length returns the number of values in the array.

Sample Code initializing the vlaues. // Fig. 7.3: InitArray.java // Initializing the elements of an array with an array initializer. public class InitArray { public static void main( String args[] ) { // initializer list specifies the value for each element int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; System.out.printf( "%s%8s\n", "Index", "Value" ); // column headings // output each array element's value for ( int counter = 0; counter < array.length; counter++ ) System.out.printf( "%5d%8d\n", counter, array[ counter ] ); } // end main } // end class InitArray Note: You do not have to include the ‘new’ line. The compiler counts the initializers and sets this up for you!

Program Input: 10 scores (integers) Output: –The high score –The low score –The average –The number of scores within 3 of the average –Push: Show the numbers in order low to high Input: 10 scores and calculate the standard deviation

Standard Deviation Example. Find the standard deviation of 4, 9, 11, 12, 17, 5, 8, 12, 14 First work out the mean (Average, xbar,…): ( )/9 = Now, subtract the mean individually from each of the numbers in the question and square the result. This is equivalent to the (x - xbar)² step. x refers to the values in the question. x (x - xbar)² Now add up these results (this is the 'sigma' in the formula): Divide by n-1. n is the number of values, so in this case n-1 is 8: / 8 = And finally, square root this: 4.18