French Territory of St. Pierre CSE 114 – Computer Science I Arrays.

Slides:



Advertisements
Similar presentations
Kernighan/Ritchie: Kelley/Pohl:
Advertisements

Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Chapter 9. 2 Objectives You should be able to describe: Addresses and Pointers Array Names as Pointers Pointer Arithmetic Passing Addresses Common Programming.
Lecture 05 - Arrays. Introduction useful and powerful aggregate data structure Arrays allow us to store arbitrary sized sequences of primitive values.
Arrays Chapter 6 Chapter 6.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
Arrays CS Feb Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Chapter 9 Introduction to Arrays
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.
HST 952 Computing for Biomedical Scientists Lecture 5.
Chapter 10Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 10 l Array Basics l Arrays in Classes and Methods l Programming.
1 Week 9 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
Chapter 10. Arrays Array Basics Arrays in Classes and Methods Programming with Arrays and Classes Sorting Arrays Computer Programming with JAVA.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Problem Solving using the Java Programming Language May 2010 Mok Heng Ngee Day 5: Arrays.
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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
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.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Review of ICS 102. Lecture Objectives To review the major topics covered in ICS 102 course Refresh the memory and get ready for the new adventure of ICS.
Chapter 11. Multidimensional Arrays and Vectors Multidimensional Arrays Vectors Computer Programming with JAVA.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
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.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Multidimensional Arrays l Vectors Multidimensional Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
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.
Chapter 9 Arrays. Chapter Objectives Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of “array index.
A FIRST BOOK OF C++ CHAPTER 8 ARRAYS AND POINTERS.
 2005 Pearson Education, Inc. All rights reserved Arrays.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
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.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Arrays Chapter 7.
Chapter VII: Arrays.
Arrays in Classes and Methods
EKT472: Object Oriented Programming
Arrays Chapter 6 Array Basics Arrays in Classes and Methods
1-Dimensional Arrays 2-Dimensional Arrays => Read section 1.4
EKT150 : Computer Programming
Announcements Lab 7 due Wednesday Assignment 4 due Friday.
Arrays.
CMSC 202 Constructors Version 9/10.
Presentation transcript:

French Territory of St. Pierre CSE 114 – Computer Science I Arrays

Arrays An array is an single-named and ordered collection of data values of the same type. –Why is this important? We can store multiple data values (primitive types or objects) easily We can add to, change, remove from, and refer to this data dynamically Declaration of 7 double s and 100 int s: double score1, … score7; int grade1, grade2, … grade100; Declaration/Instantiation of size of array: double[] score; score = new double[7]; int[] grade = new int[100]; Reserves memory for this much data

double[] score; score = new double[7]; Arrays in Memory … 012…99 grade: score: indexes values int[] grade = new int[100];

int index; for (index=0; index<7; index++) score[index] = 6.0; Assign values to and access values from array variables using a subscript (index): grade[12] = 79; grade[13] = grade[12] + 10; Array assignments 89… 012…99 grade: 79… … score: 6.0 NOTE: Array subscripts start with 0!!!! An array of size N has subscripts 0, 1, …, N-1.

More about Arrays Array size is static (cannot change after instantiation) BUT array size does not have to be defined with a constant: int[] grade; int numGrades; System.out.println ("How many grades do you have?"); numGrades = keyboard.nextInt(); grade = new int[numGrades]; Initializing arrays: double[] price = {1.25, 3.15, 2.08}; int[] areaCode = new int[10]; int j; for (j=0; j<10; j++) areaCode[j]=631; What’s wrong with this? for (j=0; j<=10; j++) areaCode[j]=631; ArrayIndexOutOfBoundsException

Arrays and Objects An array is an object (basically): int[] grade = new int[5]; grade[0] grade[1] grade[2] MEMORY grade etc… public instance variable: length length represents the capacity of an array for (j=0; j<grade.length; j++) grade[j] = 100-j;

Subscript out of Range Error Using a subscript larger than length-1 or smaller than 0 causes a run time (not a compiler) error –an ArrayIndexOutOfBoundsException is thrown you need to fix the problem and recompile your code Other programming languages, e.g. C and C++, do not even cause a run time error! –one of the most dangerous characteristics of these languages is that they may allow out of bounds array indexes.

Array length length is specified when an array is created with new –determines the amount of memory allocated –determines the maximum number of elements (capacity) storage is allocated whether or not the elements are assigned values What would be the output? double[] score = new double[7]; System.out.println(score.length); The length is set when an array is constructed and cannot be changed unless the array is _______________ When an array is reconstructed all data is lost. 7 reconstructed.

Array size The size of a data structure refers to the number of valid elements that are in the structure (like an array) –There is no automatic mechanism to detect how many elements have been placed in an array. So what should we do? You, the programmer need to keep track! int numGrades = 0; int[] grade = new int[100]; char input; do { System.out.print("Enter a grade: " ); grade[numGrades] = Keyboard.readInt(); numGrades++; System.out.print("Continue? (y/n) "); input = keyboard.nextChar(); } while (input != 'n'); // HOW MANY ELEMENTS ARE THERE NOW? numGrades

Parameter Passing and Arrays public class Exchange {public static void swap(int x, int y) {int temp = x; x = y; y = temp; } OUTPUT: the swap doesn’t work! WHY? ints are Call-by-Value! public class SwapPrimitivesDriver {public static void main(String args[]) {int index; int[] num = {1, 3, 5, 7, 9}; Exchange.swap(num[1], num[3]); for (index=0; index<num.length; index++) System.out.print(num[index] + " "); System.out.println(); }

Parameter Passing and Arrays (cont’d) public class Exchange {public static void swap(int[] number, int a, int b) {int temp = number[a]; number[a] = number[b]; number[b] = temp; } OUTPUT: IT WORKS! WHY? Arrays are Call-by-Reference! public class SwapUsingArraysDriver {public static void main(String[] args) {int index; int[] num = {1, 3, 5, 7, 9}; Exchange.swap(num, 1, 3); for (index=0; index<num.length; index++) System.out.print(num[index] + " "); System.out.println(); }

Another Game-Playing Object public class PlayingCard { private char suit; private int rank; public PlayingCard(char initSuit, int initRank) { if ( ( initSuit == ‘C’ || initSuit ==‘D’ || initSuit == ‘H’ || initSuit ==‘S’ ) && ( initRank >= 1 && initRank <= 13 ) ) { suit = initSuit; rank = initRank; } } public char getSuit(){return suit;} public int getRank() {return rank;} }

PlayingDeck using an Array of Objects public class PlayingDeck { private PlayingCard[] deck; private int numCards = 52; public PlayingDeck() { int cardNum = 0; int suitNum, rankNum; char suitChar; deck = new PlayingCard[numCards];

// deck of cards is NOT CREATED YET!!! for (suitNum=1; suitNum<=4; suitNum++) { switch(suitNum) { case 1: suitChar=‘C’; break; case 2: suitChar=‘D’; break; case 3: suitChar=‘H’; break; case 4: suitChar=‘S’; break; } for (rankNum=1; rankNum<=13; rankNum++) { deck[cardNum] = new PlayingCard(suitChar, rankNum); cardNum++; } } // NOW IT IS!!! } // Other methods here }

Arrays and Java Arrays are used similarly in most high-level languages Array: more than a primitive type, less than an object –methods are invoked by their special subscript notation [i] most programmers do not even think of them as methods –an array variable stores a memory address works like objects when used as method arguments and return types –arrays do not have or use inheritance Arrays are a natural fit for loops, especially for loops JDK has class implementations, but you may not use them in this course: –Array, ArrayList, Arrays

Using == with arrays if(b == a) o.println("a equals b"); else o.println("a does not equal b"); The output for this code will be " a does not equal b " because the addresses of the arrays are not equal. a a[0] a[1] a[2] etc… b b[0] b[1] b[2] PrintStream o = System.out; int i; int[] a = new int[3]; int[] b = new int[3]; for(i=0; i < a.length; i++) a[i] = i; for(i=0; i < b.length; i++) b[i] = i; MEMORY etc…

Methods that Return an Array Another example of using reference (address) Actually, the array is not returned. –The address of the array is returned Example: vowels() method constructs and returns an array public static char[] vowels() {char[] newArray = new char[5]; newArray[0] = 'a'; newArray[1] = 'e'; newArray[2] = 'i'; newArray[3] = 'o'; newArray[4] = 'u'; return newArray; } public static void main(String args[]) { char[] c = vowels(); for(int i = 0; i < c.length; i++) System.out.print(c[i]); }

The heading for the main method shows a parameter that is an array of String s: public static void main(String[] args) When running a program from the command line, words after the class name are passed to the main method in the args array. java TestProgram Josephine Student For example, if the output from the command line were sent to: Arguments for the main Method public static void main(String[] args) { System.out.println(“Hello “ + args[0] + “ “ + args[1]); } Hello Josephine Student Output:

null cities[0] cities[1] cities[2] cities[3] cities[4] cities etc… MEMORY etc… Example of a Partially Filled Array Garbage values //counter has a value of 3 //cities.length has a value of 5 int counter = 0; cities[0] = “Boston”; counter++; cities[1] = “El Paso”; counter++; cities[2] = “Denver”; counter++; char c = cities[3].charAt(1); NullPointerException Runtime Error! “ Boston” “ El Paso” “ Denver” String[] cities = new String[5]; Last element, counter - 1

Multidimensional Arrays An array can have more than one "dimension" (subscript) Construction: int numExams = 5; int numStudents = 10; int[][] grade = new int[numExams][numStudents]; Assigning Values: grade[1][6] = 92; Accessing Values: int num = grade[1][6]; A 2-D array corresponds to a table or grid –one dimension is the row –the other dimension is the column –cell: an intersection of a row and column –an array element corresponds to a cell in the table

Multidimensional Arrays (cont’d) Calculate the average grade on Exam 0. sum = 0; for (i=0; i<10; i++) sum += grade[0][i]; average = Math.round(sum/10.0); A 2-dimensional array is really an array of arrays. (Each row is an array.) Each row does not have to have the same number of elements. ("ragged array")

Multidimensional Arrays (cont’d) Calculate the average grade over all exams: int rows = 5, columns = 10; int [][] grade = new int[rows][columns]; double sum = 0.0, average = 0.0;; for (int i=0; i<rows; i++) for (int j=0; j<columns; j++) sum += grade[i][j]; average = Math.round(sum/(rows * columns));