Arrays. Lecture 11 CGS 3416 Spring March 6, Lecture 11CGS 3416 Spring 2017 Arrays March 6, / 19

Similar documents
Arrays. Lecture 11 CGS 3416 Fall October 26, 2015

array Indexed same type

Arrays. Lecture 9 COP 3014 Fall October 16, 2017

Object Oriented Programming. Java-Lecture 6 - Arrays

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

Computer Science is...

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

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

Control Structures in Java if-else and switch

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

Lecture (07) Arrays. By: Dr. Ahmed ElShafee. Dr. Ahmed ElShafee, ACU : Fall 2015, Programming I

Example: Computing prime numbers

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

Review of Important Topics in CS1600. Functions Arrays C-strings

VARIABLES AND TYPES CITS1001

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

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

Control Structures in Java if-else and switch

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 26, 2017

Lecture 5: Arrays. A way to organize data. MIT AITI April 9th, 2005

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

CS 307 Midterm 2 Spring 2011

1 Lexical Considerations

Arrays. COMS W1007 Introduction to Computer Science. Christopher Conway 10 June 2003

CS115 Principles of Computer Science

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

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

FORM 2 (Please put your name and form # on the scantron!!!!)

Arrays. Eng. Mohammed Abdualal

Lecture 17. Instructor: Craig Duckett. Passing & Returning Arrays

Chapter 6 Single-dimensional Arrays

2. [20] Suppose we start declaring a Rectangle class as follows:

An overview of Java, Data types and variables

Programming with Java

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 25, 2016

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

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

Computer Programming: C++

Last Class. While loops Infinite loops Loop counters Iterations

Lexical Considerations

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS111: PROGRAMMING LANGUAGE II

Lecture 04 Introduction to pointers

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

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

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

3. Java - Language Constructs I

More on Functions. Lecture 7 COP 3014 Spring February 11, 2018

Lecture #8-10 Arrays

Array. Prepared By - Rifat Shahriyar

Arrays. Arrays (8.1) Arrays. One variable that can store a group of values of the same type. Storing a number of related values.

Computer Science & Engineering 150A Problem Solving Using Computers

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

Array Basics: Outline

Procedural Programming

Arrays. What if you have a 1000 line file? Arrays

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

ECE 122. Engineering Problem Solving with Java

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

Chapter 6. Arrays. Java Actually: A Comprehensive Primer in Programming

Arrays. Introduction to OOP with Java. Lecture 06: Introduction to OOP with Java - AKF Sep AbuKhleiF - 1

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

( &% class MyClass { }

School of Computer Science CPS109 Course Notes Set 7 Alexander Ferworn Updated Fall 15 CPS109 Course Notes 7

CMPT 126: Lecture 6 Arrays

Array. Array Declaration:

Fall 2017 CISC124 9/16/2017

Arrays in Java Multi-dimensional Arrays

Exercise: Using Numbers

LAB 12: ARRAYS (ONE DIMINSION)

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

ENCE 688R Civil Information Systems. The Java Language. Mark Austin.

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

ARRAYS(II Unit Part II)

2-D Arrays. Of course, to set each grid location to 0, we have to use a loop structure as follows (assume i and j are already defined):

type arrayname [ size type arrayname [ size ] = { item ,, item size size

CS1150 Principles of Computer Science Arrays

Variables, Types, Operations on Numbers

Lecture 15. Arrays (and For Loops)

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

1. What does the following code fragment write to the monitor?

CS Programming I: Arrays

Accelerating Information Technology Innovation

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Introduction to Programming, Aug-Dec 2006

Homework 5. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Computational Expression

CMSC131. Arrays: The Concept

Instructor: Eng.Omar Al-Nahal

Lexical Considerations

At this time we have all the pieces necessary to allocate memory for an array dynamically. Following our example, we allocate N integers as follows:

Module 7: Arrays (Single Dimensional)

Polymorphism and Interfaces. CGS 3416 Spring 2018

COMP 110 Introduction to Programming. What did we discuss?

Advanced Computer Programming

Transcription:

Arrays Lecture 11 CGS 3416 Spring 2017 March 6, 2017 Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 1 / 19

Arrays Definition: An array is an indexed collection of data elements of the same type. Indexed means that the array elements are numbered (starting at 0). The restriction of the same type is an important one, because arrays are stored in consecutive memory cells. Every cell must be the same type (and therefore, the same size). Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 2 / 19

Creating Arrays Two Steps: Declare an array variable (a reference to the array) Create the array Formatting the Array Variable type[] arrayname; type arrayname[]; // preferred // alternate form Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 3 / 19

Format for creating the array (with the operator new) arrayname = new type[size]; //type should match the type of "arrayname" Examples: int[] list = new int[30]; char[] name = new char[20]; double[] nums = new double[x]; The array s size is stored in arrayname.length. For example, the size of the list array above is: list.length Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 4 / 19

Initializing and Using Arrays When array of a built-in type is created, elements are automatically initialized. numeric types - array elements initialized to 0. char type - array elements initialized to \u0000 (unicode 0, corresponds to ASCII 0, or \0 ). boolean type - array elements initialized to false. Once an array is created, the notation arrayname[index] refers to a specific array slot the one at the given index position. Arrays are indexed from 0 through (array.length - 1). The index must be an integer or integer expression. Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 5 / 19

Some Examples int x; int[] list = new int[5]; // create array double[] nums = new double[10]; // create array list[3] = 6; // assign value 6 to array item with index 3 System.out.print(nums[2]); // output array item with index 2 list[x] = list[x+1]; // set values in list array to {1, 3, 5, 7, 9} for (int i = 0; i < list.length; i++) list[i] = i * 2 + 1; Note that this last example, the for-loop, illustrates a good way to set all values in an array. Arrays and for-loops go great together! Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 6 / 19

A Shortcut The following format can be used to declare, create, and initialize an array in one line. (Note that this also bypasses the new operation, which is implicit): type[] arrayname = { initializer list }; The initializer list is a comma-separated list of array values. From this, the compiler can figure out the number of elements when creating the array. Examples: int[] list ={2, 4, 6, 8, 10, 12, 14, 16}; //has size 8 double[] grades = {96.5, 88.4, 90.3, 70}; //has size 4 char[] vowels = { a, e, i, o, u }; //size 5 Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 7 / 19

Passing arrays to methods Array variables can be used as method parameters. Arrays are not passed by value. Recall that regular parameters are passed by value i.e. the function parameter is a local copy of the original argument passed in. When passing an array into a function, only the array reference variable is passed in. A copy of the array is not made. The parameter variable refers back to the original array. If the method makes changes to the array, it will affect the original array that was passed in. Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 8 / 19

Copying Arrays If we have these two arrays, how do we copy the contents of list2 to list1? int[] list1 = new int[5]; int[] list2 = 3, 5, 7, 9, 11; With variables, we use the assignment statement, so this would be the natural tendency but it is wrong! list1 = list2; //does NOT copy array contents We must copy between arrays element by element. A for loop makes this easy, however: for (int i = 0; i < list2.length; i++) list1[i] = list2[i]; Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 9 / 19

Copying Arrays There is also a static method called arraycopy in the java.lang.system class. It s format is: arraycopy(srcarray, src pos, tararray, tar pos, len); src pos and tar pos indicate the starting positions to use in the copy process. len is the number of elements to be copied. Sample call: //this is equivalent to the for-loop example above System.arraycopy(list2, 0, list1, 0, list2.length); Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 10 / 19

Multi-dimensional Arrays Use separate set of index brackets [ ] for each dimension. Examples: // a 5 x 3 table of integers int[][] table = new int[5][3]; // a 4 x 3 matrix of short integers short[][] matrix = { {3, 4, 5}, {1, 2, 3}, {0, 5, 9}, {8, 1, -2} }; Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 11 / 19

Multi Dimensional Arrays create the single reference nums int [][] nums; create the array of references nums = new int[5][]; this create the second level of arrays for (int i=0; i < 5 ; i++) nums[i] = new int[4]; // create arrays of integers you must always specify the first dimension nums = new int[][]; // ILLEGAL - NEEDS 1ST DIMENSION you do not need to specify the second dimension nums = new int[5][]; // OK nums = new int[5][4]; // OK Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 12 / 19

Multi Dimensional Arrays For a 2 dimensional array, we usually think of the first size as rows, and the second as columns, but it really does not matter, as long as you are consistent! We could think of the first array above as a table with 5 rows and 3 columns, for example. When using a multi-dimensional array, make sure that the indices are always used in the same order: table[3][1] = 5; // assigns a 5 to "row 3, column 1", in the above interpretation Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 13 / 19

Higher Dimensional Arrays One can create arrays of higher dimension than 2. For example, if we were measuring the temperature in a rectangular volume. int temperature[][][] = new int[10][20][30];// This creates an array of 10x20x30=6000 integers. temperature is an array of array of arrays All but the last dimension must be initially specified: int temperature[][][] = new int[10][10][]; // OK int temperature[][][] = new int[10][][]; // NOT OK Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 14 / 19

Enhanced for loops The enhanced for statement allows us to iterate through any array or collection without using a counter, the traditional index through the array. Format (for arrays): for ( parameter : arrayname) loop body Consider a typical loop for adding up the elements of a numerical array: int[] values = new int[10]; // other statements that load array with data... int total = 0; for (int i = 0; i < values.length; i++) total = total + values[i]; System.out.println("The total is " + total); Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 15 / 19

Enhanced for loop The following code is equivalent, using an enhanced for loop: int[] values = new int[10]; // other statements that load array with data... int total = 0; for (int number : values) total = total + number; System.out.println("The total is " + total); Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 16 / 19

Variable-Length Parameter Lists A method can have an unspecified number of arguments, of a specified type. To do this, follow the type name with an ellipsis (...) Format: typename... variablename The use of the ellipsis can only occur once in a parameter list, and must be at the end. void dothing(int x, double... values) //LEGAL void dothing(double... values, int size) // ILLEGAL void dothing(double... x, int... numbers)// ILLEGAL Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 17 / 19

Variable-Length Parameter Lists In the dothing method above, a variable amount of double arguments may be passed in. The following are all legal calls: double d1, d2, d3, d4; dothing(5, d1, d2); dothing(5, d1, d2, d3); dothing(5, d1, d2, d3, d4); dothing(5, d1, d2, d3, d4, 3.4, 5.9, 12.4); Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 18 / 19

Variable-Length Parameter Lists Java treats a variable-length list of arguments like an array of items of the same type, so enhanced for-loops can be used on them. void printstats(double... values) { for (double val : values) System.out.print(val + " "); } Lecture 11CGS 3416 Spring 2017 Arrays March 6, 2017 19 / 19