array Indexed same type

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

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

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

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

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

Computer Science is...

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

Lecture #8-10 Arrays

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

Chapter 6 Single-Dimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Example: Computing prime numbers

Module 7: Arrays (Single Dimensional)

CS115 Principles of Computer Science

Last Class. While loops Infinite loops Loop counters Iterations

Chapter 7 Single-Dimensional Arrays

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

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved

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

1 Lexical Considerations

Announcements. PS 4 is ready, due next Thursday, 9:00pm. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

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

Lexical Considerations

VARIABLES AND TYPES CITS1001

Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world

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

Full file at

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

Opening Problem EXAMPLE. 1. Read one hundred numbers, 2. compute their average, and 3. find out how many numbers are above the average.

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

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Computational Expression

Lexical Considerations

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

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

14. Array Basics. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

CS1150 Principles of Computer Science Arrays

Getting started with Java

CMSC131. A Simple Problem?

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

Programming with Java

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

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

printf( Please enter another number: ); scanf( %d, &num2);

CMSC 330: Organization of Programming Languages. OCaml Imperative Programming

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

Chapter 7 Array. Array. C++, How to Program

1007 Imperative Programming Part II

CHAPTER 7 ARRAYS: SETS OF SIMILAR DATA ITEMS

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

CS1150 Principles of Computer Science Arrays

Arrays. Eng. Mohammed Abdualal

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

ECE 122. Engineering Problem Solving with Java

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

Instructor: Eng.Omar Al-Nahal

Chapter 6 Single-dimensional Arrays

PROGRAMMING FUNDAMENTALS

LAB 12: ARRAYS (ONE DIMINSION)

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

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

Section 2: Introduction to Java. Historical note

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

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

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

Chapter 7: Single-Dimensional Arrays. Declaring Array Variables. Creating Arrays. Declaring and Creating in One Step.

Introduction to Programming Using Java (98-388)

CS111: PROGRAMMING LANGUAGE II

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Chapter 9 Introduction to Arrays. Fundamentals of Java

Fall 2017 CISC124 9/16/2017

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

Arrays in Java Multi-dimensional Arrays

CMPT 126: Lecture 6 Arrays

Arrays and ArrayLists. David Greenstein Monta Vista High School

Arrays (Deitel chapter 7)

Basics of Java Programming

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

ARRAYS(II Unit Part II)

Data dependent execution order data dependent control flow

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

Chapter 02: Using Data

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

Arrays and functions Multidimensional arrays Sorting and algorithm efficiency

CS313D: ADVANCED PROGRAMMING LANGUAGE

More non-primitive types Lesson 06

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

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

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

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Control Structures in Java if-else and switch

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

Visual C# Instructor s Manual Table of Contents

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

Advanced Computer Programming

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

Unit 2: Java in the small. Prepared by: Dr. Abdallah Mohamed, AOU-KW

Transcription:

ARRAYS Spring 2019

ARRAY BASICS An array is an indexed collection of data elements of the same type Indexed means that the elements are numbered (starting at 0) The restriction of the same type is important, as arrays are stored in consecutive memory cells. By making sure they are the same type, you also make sure they are of the same size

CREATING ARRAYS Two steps: 1. Declare an array variable 2. Create the array (with the operator new) Formats for declaring the array variable: type[] arrayname; type arrayname[]; Format for creating the array: arrayname = new type[size]; Examples: int[] list; list = new int[30]; //preferred //alternate //declare the array variable list //creates an array of 30 integers double[] num; nums = new double[x]; //declare the array variable nums //creates an array of x doubles

CREATING ARRAYS CONT. Combined format: type[] arrayname = new type[size]; Examples: int[] list = new int[30]; char[] name = new char[20]; double[] nums = new double[x]; Notice that the size can be a variable, as all arrays are created dynamically in Java The array s size is stored in arrayname.length. For example, the size of the array named list is: list.length

INITIALIZING AND USING ARRAYS When an array of a built-in type is created, elements are initialized automatically numeric types elements are all 0 char type elements initialized to Unicode 0, \0, \u0000 boolean type each element is false Here is an example illustrating automatic initialization Once created, reference a specific element at a given index position using arrayname[index] Array indices go from 0 to (array.length - 1) The index must be an integer or integer expression 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 at 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;

INITIALIZER LISTS You can declare, create, and initialize an array in one line (in this case, the new operation is implicit): type[] arrayname = { initializer list }; The initializer list is a comma-separated list of array values. The compiler determines the number of elements in the array using this list. Examples: int[] list = {2, 4, 6, 8, 10, 12, 14, 16}; // has size 8 double[] grades = {96.5, 88.4, 90.3, 70.1}; // has size 4 char[] vowels = {'a', 'e', 'i', 'o', 'u'}; // size 5

PASSING ARRAYS Array variables can be used as method parameters The arrays themselves are not passed by value; but their reference variables are Regular parameters (of built-in primitive types) are passed by value When passing an array into a function, only the array reference variable is passed in A copy of the array is not made, just a copy of the reference variable Parameter variable refers to the original array, so changes to the array in the method will affect the original array Assigning a new array to the reference variable inside the method will not change the original reference variable/array Note: Pass-by-value vs. pass-by-reference is a complicated subject when discussing Java. Technically, all Java parameters are passed by value, but because all non-primitives are dynamically allocated, it leads to semantics that are very similar to pass-by-reference in a lot of cases, but not all. See here for one explanation if you re curious. Or here

COPYING ARRAYS Given two arrays, copying the contents of one to the other is slightly more complicated than dealing with primitive types. For example, if we have these two arrays: int[] list1 = new int[5]; int[] list2 = {3, 5, 7, 9, 11}; Then this notation does NOT copy the array contents: list1 = list2; We must copy element-by-element. For loops are an easy and common way to do this: for (int i = 0; i < list2.length; i++) list1[i] = list2[i]; We can also use the arraycopy method in the java.lang.system class. It has the format: arraycopy(sourcearray, src_pos, targetarray, tar_pos, length); src_pos and tar_pos indicate the starting position to use in the copy process. length is the number of elements to be copied. This call is the same as the for-loop above: System.arraycopy(list2, 0, list1, 0, list2.length);

MULTI-DIMENSIONAL ARRAYS For multi-dimensional arrays, you use a different set of index brackets for each dimension Remember that multi-dimensional arrays are effectively arrays of arrays For a 2d array, we often think of the first index as rows and the second as columns, but all that matters is being consistent. So, when using a multi-dimensional array, make sure that the indices are always used in the same order. int[][] table = new int[5][3]; short[][] matrix = { {3, 4, 5}, {1, 2, 3}, {0, 5, 9}, // a 5 x 3 table of integers {8, 1, -2} }; // a 4 x 3 matrix of short integers table[3][1] = 5; // assigns a 5 to "row 3, column 1", in one interpretation Examples copying arrays and using 2D arrays

ENHANCED for LOOPS The enhanced for statement allows us to iterate through any array or collection without using a counter (added in Java 1.5) Note that using this version of a for loop is always good for ACCESSING array elements, but not always useful for MODIFYING the array elements There are some cases where it is possible (when the elements in the array/collection are mutable objects and you are using member functions to change them), but you may not change primitives or use assignment statements to change the elements As a general rule, use an enhanced for loop if you are looping in the first-to-last element order, do not need the loop index, and do not need to do any assignment to the array elements or change an immutable object. Format (for arrays): for ( parameter : arrayname ) Loop body

ENHANCED for LOOPS This, a typical loop for adding up the elements of an array: int [] values = new int[10]; //More statements to load the array int total = 0; for (int i = 0; i < values.length; i++) total = total + values[i]; System.out.println( The total is + total); Is equivalent to this, 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); Array3.java code example using enhanced for loops

VARIABLE-LENGTH PARAMETER LISTS A method can have an unspecified number of arguments of a specified type (this feature was also added in Java 1.5) To do this, follow the type name with an ellipsis ( ) typename variablename The use of the ellipsis can only occur once in a parameter list and it must be at the end, similar to default parameters in C++ void dotask(int x, double... values) // LEGAL void dothing(double... values, int size) void dothing(double... values, int... numbers) // ILLEGAL // ILLEGAL In the legal dotask method above, a variable number of arguments may be passed in. These are all legal calls: double d1, d2, d3, d4; //some assignment statements to the variables dotask(5, d1, d2); dotask(5, d1, d2, d3); dotask(5, d1, d2, d3, d4); dotask(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. These are often handled using for loops. Since they are arrays, enhanced for loops can be used on them, as well. void printstats(double values) { for (double val: values) System.out.print(val + ); } Example

EXAMPLES I will often provide a link to the code examples from the book that are related to the notes. I will sometimes go through some of them in class, but most are just there for your reference. One thing of note in this set is shown in example 7.7 (fig07_07). As of Java 7, Java will ignore underscores (_) in numeric literals, so you can use them to make large numbers easier to read. In this example, they use 60_000_000 instead of 60000000, as it makes it more obvious it is 60 million at a glance. Some code examples from Deitel (Chapter 7)