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

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

Computer Programming: C++

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

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

Arrays. Chapter 7 (Done right after 4 arrays and loops go together, especially for loops)

Outline. What s wrong with Enumerations? Indexing Searching Self-Organizing Vectors Binary Searching Sorting Command line Arguments.

CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, Name:

Outline. 14. Organization. Programming in Java. Computer Science Dept Va Tech August D Barnette, B Keller & P Schoenhoff

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

Initializers: Array initializers can be used with class base types as well. The elements of the initializer can be expressions (not just constants).

Advanced Computer Programming

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

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

CMSC 341. Nilanjan Banerjee

Computer Science & Engineering 150A Problem Solving Using Computers

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

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

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

Array. Prepared By - Rifat Shahriyar

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

Computer Programming, I. Laboratory Manual. Final Exam Solution

Introduction to Programming Using Java (98-388)

University of Palestine. Mid Exam Total Grade: 100

CSE 142 Su01 Final Exam Sample Solution page 1 of 7

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

CSE 143 SAMPLE MIDTERM SOLUTION

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

Lecture 07, Fall 2018 Wednesday September 19

Introduction to Object-Oriented Programming

Question: Total Points: Score:

COMP 110/L Lecture 13. Kyle Dewey

Last Name: Circle One: OCW Non-OCW

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Fall 2017 CISC124 9/16/2017

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

Algorithms for Arrays Vectors Pointers CS 16: Solving Problems with Computers I Lecture #14

Programming overview

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

CIS 120 Midterm II November 16, 2012 SOLUTIONS

Java is an objet-oriented programming language providing features that support

Introduction to Object-Oriented Programming

Lecture 05: Methods. AITI Nigeria Summer 2012 University of Lagos.

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2013

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

Instructor: Eng.Omar Al-Nahal

Introduction to Programming (CS112): Sample

Linked Lists. private int num; // payload for the node private Node next; // pointer to the next node in the list }

More on methods and variables. Fundamentals of Computer Science Keith Vertanen

Declaring and ini,alizing 2D arrays

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

ECE 242 Fall 13 Exam I Profs. Wolf and Tessier

Fundamental problem in computing science. putting a collection of items in order. Often used as part of another algorithm

Arrays. Eng. Mohammed Abdualal

Final Exam. COMP Summer I June 26, points

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

Class, Variable, Constructor, Object, Method Questions

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Birkbeck (University of London) Software and Programming 1 In-class Test Mar Answer ALL Questions

About this exam review

CS171:Introduction to Computer Science II

CIS 120 Midterm II November 8, Name (printed): Pennkey (login id):

Final Exam COMP Fall 2004 Dec 16, 2004

Objectives. Order (sort) the elements of an array Search an array for a particular item Define, use multidimensional array

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

JAVA Programming Language Homework II Student ID: Name:

Lab Assignment Three

AP Computer Science A Unit 7. Notes on Arrays

Enums. In this article from my free Java 8 course, I will talk about the enum. Enums are constant values that can never be changed.

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Array Basics: Outline

Learning objec-ves. Declaring and ini-alizing 2D arrays. Prin-ng 2D arrays. Using 2D arrays Decomposi-on of a solu-on into objects and methods

Faculty of Science FINAL EXAMINATION

CS61B, Spring 2003 Discussion #17 Amir Kamil UC Berkeley 5/12/03

Practice Questions for Chapter 9

JAVA Programming Language Homework I - OO concept

CS 307 Midterm 2 Spring 2008

1.00 Lecture 8. Using An Existing Class, cont.

Java Fundamentals (II)

FAQ: Classes & Objects

Array Based Lists. Collections

Programming Language Concepts: Lecture 2

1.00 Introduction to Computers and Engineering Problem Solving. Quiz 1 March 7, 2003

CS125 : Introduction to Computer Science. Lecture Notes #6 Compound Statements, Scope, and Advanced Conditionals

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

Computer Science II (20082) Week 1: Review and Inheritance

( &% class MyClass { }

LECTURE 17. Array Searching and Sorting

Center for Computation & Louisiana State University -

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2013

(a) Assume that in a certain country, tax is payable at the following rates:

Computer Science 1 Honors

Introduction to Computer Science II (CSI 1101)

Collections. Collections Collection types Collection wrappers Composite classes revisited Collection classes Hashtables Enumerations

Searching & Sorting in Java Bubble Sort

SCJ2013 Data Structure & Algorithms. Bubble Sort. Nor Bahiah Hj Ahmad & Dayang Norhayati A. Jawawi

CS 231 Data Structures and Algorithms, Fall 2016

CSCI 135 Exam #1 Fundamentals of Computer Science I Fall 2014

Transcription:

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

Arrays An array is a list of values. In Java, the components of an array can be of any type, basic or object. An array is a special kind of object with special language support. int[] nums = new int[3] ; Arrays have special constructor: new int[3] creates a 3-element array of int. You can access the elements of the array using the [] operator, starting with element 0. nums[0] = 12 ; nums[1] = 701 ; nums[2] = 5 ;

Arrays in Memory The declaration of an n-element array sets aside n adjacent slots in memory.

Accessing Arrays The position of an element in an array is called its array index. The index of the first element in an array is 0. The index of the ith element in an array is i 1. The index of the last element in an n-element array is n 1. The number of elements in an array is available in a public instance field named length. Bounds-checking is done on array indices at run time.

public void printints(int[] nums) { for( int i=0 ; i < nums.length ; i++ ) System.out.println(nums[i]) ; } public void printlastx(int[] nums) { System.out.println( nums[nums.length] ) ; /* Error: nums.length exceeds array bounds */ } public void printlast(int[] nums) { System.out.println( nums[nums.length-1] ) ; }

Array Declarations int[] is a type array of int distinct from int. int[] a, b, c ; /* Declares 3 arrays: a, b and c */ Alternatively, you can place the brackets next to the identifier. int a[], b, c ; /* Declares 1 array: a and two ints: b and c */

Array Declarations: 2 Arrays are like any other object: the value of an array variable is null until you create an array object using new. int[] grades ; int n = grades.length ; /* Error: can t access null array */ grade = new int[20] ; n = grades.length ; /* OK: n=20 */

Array Elements The elements of an array are just like any regular variable of their type. Once you ve indexed the array, you can do all the normal things. int[] nums = new int[100] ; boolean[] flags = new boolean[10] ; Foo foos = new Foo[12] ; int i, j, k ;... if( boolean[i] ) nums[i] = nums[j]++ * foos[k].getx() ;

Arrays of Objects When you create an array of objects, all of the elements are set to null. You need to create an instance for each element individually. Foo foos = new Foo[12] ; for( int i=0 ; i < foos.length ; i++ ) foos[i] = new Foo() ;

Array Initializers If you know the values of the elements at compile time, you can create and initialize an array without using new. int[] grades = { 87, 66, 93 } ; is the same as int[] grades = new int[3] grades[0] = 87 ; grades[1] = 66 ; grades[2] = 93 ;

Array Parameters Arrays are like any other object parameter: the reference is immutable, but the elements can change. /* This method will successfully reverse the elements in an array */ public void reverse(int[] nums) { for( int i=0 ; i < nums.length/2 ; i++ ) { int tmp = nums[i] ; nums[i] = nums[nums.length-(i+1)] ; nums[nums.length-(i+1)] = tmp ; } }

/* This method tries to change the reference. */ public void reversex(int[] nums) { int[] nums2 = new int[nums.length] ; for( int i=0 ; i < nums.length ; i++ ) nums2[i] = nums[nums.length-(i+1)] ; nums = nums2 ; } /* If we return the second array, it will work */ public int[] reverse2(int[] nums) { int[] nums2 = new int[nums.length] ; for( int i=0 ; i < nums.length ; i++ ) nums2[i] = nums[nums.length-(i+1)] ; return nums2 ; }

Command-line Arguments Now we know everything we need to understand the signature of the main method. public static void main(string[] args) {... } The parameter args is an array of String. The elements of args are the command-line arguments used to run the class.

public class CommandLine { public static void main(string[] args) { for( int i=0 ; i < args.length ; i++ ) System.out.println(i+": "+args[i]+" ") ; } } % java CommandLine -t --foo=bar out.file 0: -t 1: --foo=bar 2: out.file

Two-dimensional Arrays You can make an array of any kind of object, including arrays. We call an array of arrays a two-dimensional array. public class TicTacToe { public static final int EMPTY = 0 ; public static final int X = 1 ; public static final int O = 2 ; } private int[][] board = { {EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY}, {EMPTY, EMPTY, EMPTY} } ;...

Two-dimensional Arrays: 2 You can create an entire 2-D array with one call to new, or you can create each inner array separately. The inner arrays don t necessarily have to be the same size. /* Full 10x12 array of int */ int[][] matrix = new int[10][12] ; /* Create the "outer" array first */ int[][] ragged = new int[5][] ; /* Inner arrays are of lengths 1, 2, 3, 4 and 5 */ for( int i=0 ; i < ragged.length ; i++ ) ragged[i] = new int[i+1] ;

Multi-dimensional Arrays There s no reason you can t create arrays of 3, 4 and 5 dimensions ( an array of arrays of arrays of arrays... ), but beyond 2 dimensions, they get harder and harder to manage. Before you create a many-dimensional array, think hard about other ways to attack the problem. Often, an object carrying all the same information is a better idea.

Sorting Integers Now that we can make lists of things using arrays, we might like to be able to organize our lists. A sorting algorithm takes an unordered array of objects and returns an array of objects in ascending or descending order. What constitutes ascending order on a general object Foo is not always clear, so for now we ll concentrate on integers.

Bubble Sort Input: List of integers X 0, X 1,..., X n. Output: X 0, X 1,..., X n in ascending order. 1. i := 0, swap := 0 2. If X i > X i+1, swap X i and X i+1, swap := 1. 3. i := i + 1 4. If i < n, go to Step 2. 5. If swap > 0, go to Step 1. 6. Return sorted list X.

Bubble Sort: Example 5 9 2 1 6 5 9 2 1 6 5 2 9 1 6 5 2 9 1 6 5 2 1 9 6 5 2 1 9 6 5 2 1 6 9 5 2 1 6 9 2 5 1 6 9 2 5 1 6 9 2 1 5 6 9 2 1 5 6 9 2 1 5 6 9 2 1 5 6 9 1 2 5 6 9 1 2 5 6 9 1 2 5 6 9 1 2 5 6 9 1 2 5 6 9

Selection Sort Input: List of integers X 0, X 1,..., X n. Output: X 0, X 1,..., X n in ascending order. 1. i := 0. 2. Find the index j of the minimum item, such that j i. 3. Swap X i and X j. 4. i := i + 1 5. If i < n, go to Step 1. 6. Return sorted list X.

Selection Sort: Example 5 9 2 1 6 1 9 2 5 6 1 9 2 5 6 1 2 9 5 6 1 2 9 5 6 1 2 5 9 6 1 2 5 9 6 1 2 5 6 9 1 2 5 6 9

Insertion Sort Input: List of integers X 0, X 1,..., X n. Output: X 0, X 1,..., X n in ascending order. 1. i := 1. 2. n := X i, j := i 1. 3. If X j n or j < 0, go to Step 5. 4. X j+1 := X j, j := j 1, go to Step 3. 5. X j+1 := n, i := i + 1. 6. If i < n, go to Step 2. 7. Return sorted list X.

Insertion Sort: Example 5 9 2 1 6 5 9 2 1 6 2 5 9 1 6 1 2 5 9 6 1 2 5 6 9