Arrays. Lecture 11 CGS 3416 Fall October 26, 2015

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

array Indexed same type

Arrays. Lecture 9 COP 3014 Fall October 16, 2017

Object Oriented Programming. Java-Lecture 6 - Arrays

Computer Science is...

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

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. Lecture 4 COP 3014 Fall September 18, 2017

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

VARIABLES AND TYPES CITS1001

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

Example: Computing prime numbers

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

Control Structures in Java if-else and switch

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Control Structures in Java if-else and switch

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

Computer Programming: C++

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

CS115 Principles of Computer Science

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

1 Lexical Considerations

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

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

Chapter 6 Single-dimensional Arrays

An overview of Java, Data types and variables

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

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

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

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

Computer Science & Engineering 150A Problem Solving Using Computers

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

Last Class. While loops Infinite loops Loop counters Iterations

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

Fall 2017 CISC124 9/16/2017

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

Lecture 04 Introduction to pointers

CS313D: ADVANCED PROGRAMMING LANGUAGE

3. Java - Language Constructs I

Lexical Considerations

CS111: PROGRAMMING LANGUAGE II

Lecture #8-10 Arrays

CS Programming I: Arrays

CS 307 Midterm 2 Spring 2011

Lexical Considerations

Programming with Java

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

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

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

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

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

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

LAB 12: ARRAYS (ONE DIMINSION)

Array. Array Declaration:

( &% class MyClass { }

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

ECE 122. Engineering Problem Solving with Java

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

CMPT 126: Lecture 6 Arrays

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

Exercise: Using Numbers

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

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

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):

ARRAYS(II Unit Part II)

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

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

Lecture 14. 'for' loops and Arrays

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

Variables, Types, Operations on Numbers

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

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

Computational Expression

Module 7: Arrays (Single Dimensional)

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Lecture 15. Arrays (and For Loops)

COMP 110 Introduction to Programming. What did we discuss?

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:

Advanced Computer Programming

Computer Programming, I. Laboratory Manual. Final Exam Solution

Lab 3. Pointers Programming Lab (Using C) XU Silei

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

More non-primitive types Lesson 06

Summer May 18, 2010

The University Of Michigan. EECS402 Lecture 05. Andrew M. Morgan. Savitch Ch. 5 Arrays Multi-Dimensional Arrays. Consider This Program

Programming Projects: 2.1, 2.3, 2.4, 2.7, 2.8, 2.13

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.

Following is the general form of a typical decision making structure found in most of the programming languages:

Procedural Programming

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

Lecture 13 & 14. Single Dimensional Arrays. Dr. Martin O Connor CA166

CPSC 427: Object-Oriented Programming

Abstract Data Type (ADT) & ARRAYS ALGORITHMS & DATA STRUCTURES I COMP 221

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #44. Multidimensional Array and pointers

Chapter-8 DATA TYPES. Introduction. Variable:

Transcription:

Arrays Lecture 11 CGS 3416 Fall 2015 October 26, 2015

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).

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

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

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.

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!

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

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.

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];

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);

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} };

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

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);

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);

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 dotask(int x, double... values) //LEGAL void dothing(double... values, int size) // ILLEGAL void dothing(double... x, int... numbers)// ILLEGAL

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);

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 + " "); }