CS1020 Data Structures and Algorithms I Lecture Note #2 Arrays.

Slides:



Advertisements
Similar presentations
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
Advertisements

1 Various Methods of Populating Arrays Randomly generated integers.
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
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.
Lecture 15 Arrays: Part 1 COMP1681 / SE15 Introduction to Programming.
CS1020 Data Structures and Algorithms I Lecture Note #4 Collection of Data.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
Java Unit 9: Arrays Declaring and Processing Arrays.
CS1101: Programming Methodology Aaron Tan.
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
A First Book of ANSI C Fourth Edition
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Programming Fundamentals I (COSC-1336), Lecture 8 (prepared after Chapter 7 of Liang’s 2011 textbook) Stefan Andrei 4/23/2017 COSC-1336, Lecture 8.
Problem Solving using the Java Programming Language May 2010 Mok Heng Ngee Day 5: Arrays.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Array Cs212: DataStructures Lab 2. Array Group of contiguous memory locations Each memory location has same name Each memory location has same type a.
BUILDING JAVA PROGRAMS CHAPTER 7 Arrays. Exam #2: Chapters 1-6 Thursday Dec. 4th.
UNIT 14 Functions with Pointer Parameters.
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.
CS1101: Programming Methodology Aaron Tan.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
Types in Java 8 Primitive Types –byte, short, int, long –float, double –boolean –Char Also some Object types: e.g. “String” But only single items. What.
Collection of Data. Objectives [CS1020 Lecture 4: Collection of Data] 2 Using arrays Generics: Allowing operations not tired to a specific data type Classes:
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Array Objectives To understand the concept of arrays To understand the purpose to which we use arrays. To be able to declare references to arrays. To be.
WEEK 6 Class Activities Lecturer’s slides.
Chapter 8: Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading:
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 7.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
UNIT 10 Multidimensional Arrays.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
WEEK 8 Class Activities Lecturer’s slides.
CS1101: Programming Methodology
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CS1020 Data Structures and Algorithms I Lecture Note #6 Vector and ArrayList.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
CS 116: Object Oriented Programming II. Topics Vectors Multidimensional Arrays ArrayList.
Week 6 - Friday.  What did we talk about last time?  Loop examples.
Array and String.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
Introduction to programming in java Lecture 22 Arrays – Part 2 and Assignment No. 3.
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.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Basic arrays, binary search, selection sort by amelia bateman
CS1010 Programming Methodology
EKT150 : Computer Programming
Object Oriented Programming in java
Building Java Programs
OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
Building Java Programs
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
CS 200 Objects and ArrayList
Data Structures and Algorithms 2/2561
Week 7 - Monday CS 121.
Presentation transcript:

CS1020 Data Structures and Algorithms I Lecture Note #2 Arrays

Objectives [CS1020 Lecture 2: Arrays] 2 Using arrays to organise data.

References 3 Book Array: Chapter 1, Section 1.1, pages 35 to 38 CS1020 website  Resources  Lectures ~cs1020/2_resources/lectures.htmlhttp:// ~cs1020/2_resources/lectures.html [CS1020 Lecture 2: Arrays]

Outline 1.Array 1.1Introduction 1.2Array in C 1.3Array in Java 1.4Array as a Parameter 1.5Detour: String[] in main() method 1.6Returning an Array 1.7Common Mistakes 1.82D Array 1.9Drawback 4 [CS1020 Lecture 2: Arrays]

1 Array A collection of homogeneous data

Introduction 6 1. Array Array is the simplest way to store a collection of data of the same type (homogeneous) It stores its elements in contiguous memory  Array index begins from zero  Example of a 5-element integer array A with elements filled A 24 A[0] 7 A[1] -3 A[2] 15 A[3] 9 A[4] [CS1020 Lecture 2: Arrays]

Array in C (1/2) 7 #include #define MAX 6 int scanArray(double [], int); void printArray(double [], int); double sumArray(double [], int); int main(void) { double list[MAX]; int size; size = scanArray(list, MAX); printArray(list, size); printf("Sum = %f\n", sumArray(list, size)); return 0; } // To read values into arr and return // the number of elements read. int scanArray(double arr[], int max_size) { int size, i; printf("How many elements? "); scanf("%d", &size); if (size > max_size) { printf("Exceeded max; you may only enter"); printf(" %d values.\n", max_size); size = max_size; } printf("Enter %d values: ", size); for (i=0; i<size; i++) { scanf("%lf", &arr[i]); } return size; } sum_array.c 1. Array [CS1020 Lecture 2: Arrays]

Array in C (2/2) 8 1. Array // To print values of arr void printArray(double arr[], int size) { int i; for (i=0; i<size; i++) printf("%f ", arr[i]); printf("\n"); } // To compute sum of all elements in arr double sumArray(double arr[], int size) { int i; double sum = 0.0; for (i=0; i<size; i++) sum += arr[i]; return sum; } sum_array.c [CS1020 Lecture 2: Arrays]

Array in Java (1/2) 9 1. Array In Java, array is an object. Every array has a public length attribute (it is not a method!) public class TestArray1 { public static void main(String[] args) { int[] arr; // arr is a reference // create a new integer array with 3 elements // arr now refers (points) to this new array arr = new int[3]; // using the length attribute System.out.println("Length = " + arr.length); arr[0] = 100; arr[1] = arr[0] - 37; arr[2] = arr[1] / 2; for (int i=0; i<arr.length; i++) System.out.println("arr[" + i + "] = " + arr[i]); } TestArray1.java Declaring an array: datatype[] array_name Constructing an array: array_name = new datatype[size] Accessing individual array elements. Length = ? arr[0] = ? arr[1] = ? arr[2] = ?  [CS1020 Lecture 2: Arrays]

Array in Java (2/2) Array Alternative loop syntax for accessing array elements Illustrate toString() method in Arrays class to print an array public class TestArray2 { public static void main(String[] args) { // Construct and initialise array double[] arr = { 35.1, 21, 57.7, 18.3 }; // using the length attribute System.out.println("Length = " + arr.length); for (int i=0; i<arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); // Alternative way for (double element: arr) { System.out.print(element + " "); } System.out.println(); System.out.println(Arrays.toString(arr)); } TestArray2.java Length = [35.1, 21.0, 57.7, 18.3] Using toString() method in Arrays class Syntax (enhanced for-loop): for (datatype e: array_name) Go through all elements in the array. “e” automatically refers to the array element sequentially in each iteration [CS1020 Lecture 2: Arrays]

Array as a Parameter Array public class TestArray3 { public static void main(String[] args) { int[] list = { 22, 55, 33 }; swap(list, 0, 2); for (int element: list) System.out.print(element + " "); System.out.println(); } // To swap arr[i] with arr[j] public static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j];arr[j] = temp; } TestArray3.java The reference to the array is passed into a method  Any modification of the elements in the method will affect the actual array  [CS1020 Lecture 2: Arrays]

Detour: String[] in main() method Array The main() method contains a parameter which is an array of String objects We can use this for command-line arguments public class TestCommandLineArgs { public static void main(String[] args) { for (int i=0; i<args.length; i++) System.out.println("args[" + i + "] = " + args[i]); } TestCommandLineArgs.java java TestCommandLineArgs The "Harry Potter" series has 7 books. args[0] = The args[1] = Harry Potter args[2] = series args[3] = has args[4] = 7 args[5] = books. [CS1020 Lecture 2: Arrays]

Returning an Array Array Array can be returned from a method public class TestArray4 { public static void main(String[] args) { double[] values; values = makeArray(5, 999.0); for (double value: values) { System.out.println(value + " "); } // To create an array and return it to caller public static double[] makeArray(int size, double limit) { double[] arr = new double[size]; for (int i=0; i < arr.length; i++) arr[i] = limit/(i+1); return arr; } TestArray4.java Return type: datatype[] [CS1020 Lecture 2: Arrays]

Common Mistakes (1/3) Array length versus length()  To obtain length of a String object str, we use the length() method Example: str.length()  To obtain length (size) of an array arr, we use the length attribute Example: arr.length Array index out of range  Beware of ArrayIndexOutOfBoundsException public static void main(String[] args) { int[] numbers = new int[10];... for (int i = 1; i <= numbers.length; i++) System.out.println(numbers[i]); } [CS1020 Lecture 2: Arrays]

Common Mistakes (2/3) Array When you have an array of objects, it’s very common to forget to instantiate the array’s objects. Programmers often instantiate the array itself and then think they’re done – that leads to java.lang.NullPointerException Example on next slide  It uses the Point class in the API  Refer to the API documentation for details [CS1020 Lecture 2: Arrays]

Common Mistakes (3/3) Array Point[] array = new Point[3]; for (int i=0; i<array.length; i++) { array[i].setLocation(1,2); } array null There are no objects referred to by array[0], array[1], and array[2], so how to call setLocation() on them?! Point[] array = new Point[3]; for (int i=0; i<array.length; i++) { array[i] = new Point(); array[i].setLocation(1,2); } Corrected code: array 0 x 0 y 0 x 0 y x 0 0 y 2 1 [CS1020 Lecture 2: Arrays]

2D Array (1/2) Array A two-dimensional (2D) array is an array of array. This allows for rows of different lengths. int[][] array2D = { {4,5,2}, {1,3}, {7,1,5,6} }; array2D // an array of 12 arrays of int int[][] products = new int[12][]; [CS1020 Lecture 2: Arrays]

2D Array (2/2) Array public class Test2DArray { public static void main(String[] args) { int[][] array2D = { {4, 5, 2}, {1, 3}, {7, 1, 5, 6} }; System.out.println("array2D.length = " + array2D.length); for (int i = 0; i < array2D.length; i++) System.out.println("array2D[" + i + "].length = " + array2D[i].length); for (int row = 0; row < array2D.length; row++) { for (int col = 0; col < array2D[row].length; col++) System.out.print(array2D[row][col] + " "); System.out.println(); } Test2DArray.java array2D.length = 3 array2D[0].length = ? array2D[1].length = ? array2D[2].length = ? ? array2D  [CS1020 Lecture 2: Arrays]

Drawback Array Array has one major drawback:  Once initialized, the array size is fixed  Reconstruction is required if the array size changes  To overcome such limitation, we can use some classes related to array Java has an Array class  Check API documentation and explore it yourself However, we will not be using this Array class much; we will be using some other classes such as Vector or ArrayList (to be covered later) Before doing Vector/ArrayList, we will introduce another concept later called Generics [CS1020 Lecture 2: Arrays]

Practice Exercises 20 These practice exercises are mounted on CodeCrunch this week  #04: Basic Statistics Computing mean and standard deviation  #05: Missing Digits Using array of primitive type  #06: Row and Column Sums Two-dimensional array The files are also available on the CS1020 website: You are urged to work on these exercise as they are important for you to cement your basic understanding of the topics that are covered so far [CS1020 Lecture 2: Arrays]

Missing Digits (1/2) 21 Pract. Ex. #05 [This is adapted from a CS1010 exercise in C] Write a program MissingDigits.java to read in a positive integer and list out all the digits that do not appear in the input number. (Assume input value has no leading zeroes.) You are to use primitive array, not Vector, ArrayList or any other related classes. You should use a boolean array. Sample run: Enter a number: Missing digits in 73015: [CS1020 Lecture 2: Arrays]

Missing Digits (2/2) 22 Pract. Ex. #05 What is the boolean array for? Idea?  [CS1020 Lecture 2: Arrays]

End of file