Arrays CS 180 15 Feb 2008. Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game.

Slides:



Advertisements
Similar presentations
One Dimensional Arrays
Advertisements

Arrays I Savitch Chapter 6.1: Introduction to Arrays.
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Chapter 5 Arrays and Vectors An array allows you to group data items together in a structure that is processed via an index. They allow you to process.
Arrays Chapter 6 Chapter 6.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CS102--Object Oriented Programming Lecture 5: – Arrays – Sorting: Selection Sort Copyright © 2008 Xiaoyan Li.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays in Classes and Methods l Programming.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Chapter Eight: Arrays 1.Terms and what they mean 2.Types of arrays -One Dimensional arrays -Two Dimensional arrays -ragged arrays -Parallel arrays 3. Methods.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 9 Introduction to Arrays
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
1 Week 9 l Array Basics l Arrays in Classes and Methods l Programming with Arrays and Classes l Sorting Arrays l Multidimensional Arrays Arrays.
Chapter 8 Arrays and Strings
Chapter 61 Arrays Chapter 6. 2 Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
1 Chapter 8 Multi-Dimensional Arrays. 2 1-Dimentional and 2-Dimentional Arrays In the previous chapter we used 1-dimensional arrays to model linear collections.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Lecture 5: Arrays A way to organize data MIT AITI April 9th, 2005.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
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.
JAVA: An Introduction to Problem Solving & Programming, 7 th Ed. By Walter Savitch ISBN © 2015 Pearson Education, Inc., Upper Saddle River,
IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD
Arrays Chapter 6. Objectives learn about arrays and how to use them in Java programs learn how to use array parameters and how to define methods that.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Arrays in java Unit-1 Introduction to Java. Array There are situations where we might wish to store a group of similar type of values in a variable. Array.
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
For Friday Read No quiz Program 6 due. Program 6 Any questions?
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Lecture #15 ARRAYS By Shahid Naseem (Lecturer). 2 ARRAYS DEFINITION An array is a sequence of objects of same data type. The objects in an array are also.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Introduction to programming in java Lecture 22 Arrays – Part 2 and Assignment No. 3.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
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.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Arrays Chapter 7.
Chapter 7 Part 1 Edited by JJ Shepherd
An Introduction to Java – Part I, language basics
Announcements Lab 7 due Wednesday Assignment 4 due Friday.
C++ Array 1.
Arrays.
Presentation transcript:

Arrays CS Feb 2008

Announcements Exam 1 Grades on Blackboard Project 2 scores: end of Class Project 4, due date:20 th Feb –Snakes & Ladders Game Review of Q5,Q8,Q11 & Programming Questions

Arrays: What they mean? An array is an object used to store a (possibly large) collection of data. All the data stored in the array must be of the same type. It enables you to use a single name to represent a collection of items & refer to an item by specifying the item number

Types of Arrays One-Dimensional Arrays –int students[ 5] Multi-Dimensional arrays –Simplest form is a 2-D Array int students[3 ][ 5] –Example of 3-D Array int students[ 5][7 ][ 3]

Creating an Array Declare an array – 2 forms –type arrayname[ ]; Ex: int number[ ]; –type [ ] arrayname; Ex: int [ ] number; Create memory location –arrayname= new type[size]; –Ex: number= new int[2]; –Here we have created an array of type integer with 2 elements and named it as number Put values –arrayname[index]=value; –Ex: number[0]=35; –Ex: number[1]=40;

Diagram: Creation of Array Statement int number[ ]; number=new int[2]; This is an array of length 2 “number” is a reference that points to the first memory address Result number points nowhere number number [0] number [1] Memory locations

Index / Subscript of Array –int number [i] –Here “i” is an integer used to refer to an element of the array number. It is called the Index Ex: number[0] : indicates the first element of number Ex: number[1] : indicates the second element of number Length: Instance Variable length is a public instance variable The length variable stores the number of elements the array can hold. Using Array_Name.length typically produces clearer code than using an integer literal.

Array Terminology

Array index out of bounds It is a runtime error which is caused by incorrect use of array index. –Ex: int number[]=new int[2]; –number[0]=1; –number[1]=2; –number[2]=17; Error : array “number” has just 2 elements!

Initializing Arrays An array can be initialized at the time it is declared. example double[] reading = {3, 3, 15.8, 9.7}; –The size of the array is determined by the number of values in the initializer list.

Initializing Arrays, cont. Uninitialized array elements are set to the default value of the base type. However, it’s better to use either an initializer list or a for loop. int[] count = new int[100]; for (int i = 0, i < count.length, i++) { count[i] = 0; }

Arrays in Classes & Methods Arrays can be used as instance variables in classes. Both an indexed variable of an array and an entire array can be a argument of a method. Methods can return an indexed variable of an array or an entire array.

Arrays in Classes & Methods Example class cs180Class { String studentName[], firstName[]; public cs180Class() { System.out.println("enter number of students:"); int num_students=keyboard.nextInt(); firstName = new String[num_students];... studentName = setData(firstName); } String[] setData (String name[ ]) { String[] temp = new String [name.length]; for(int i=0; i < name.length; i++) { temp[i] = name[i]; } return temp; } } Array as instance variables Array as argument of a method: Call by Value Returning an Array

What about Main method? Recall the heading for method main : public static void main(String[] args) An array of String values can be provided in the command line. example java TestProgram Mary Lou –args[0] is set to “Mary” –args[1] is set to “Lou” System.out.println(“Hello “ + args[0] + “ “ + args[1]); prints Hello Mary Lou.

Use of = & == with Arrays –The assignment operator creates an alias, not a copy of the array. –The equality operator determines if two references contain the same memory address, not if two arrays contain the same values.

Making a Copy of an Array example int[] a = new int[50]; int[] b = new int[50];... for (int j = 0; j < a.length; j++) b[j] = a[j];

Determining the “Equality” of Two Arrays To determine if two arrays at different memory locations contain the same elements in the same order, define an equals method which determines if –both arrays have the same number of elements –each element in the first array is the same as the corresponding element in the second array.

Swapping Array elements class interchange

Uses of Arrays Searching an element in a list of elements Sorting –Ascending order –Descending order –Alphabetic order

Example: Selection Sort Selection sort begins by finding the smallest item in the array and swapping it with the item in a[0].

Selection Sort: class class SelectionSort

Multi-Dimensional Arrays 2-Dimensional Array –A row & Column structure – int [ ] [ ] world= new int[10][9] –Indexing can be done using 2 integers: i, j world [i] [j] : refers to element at row i and column j Length : 2-D array –world.length: returns the # of rows –world [i].length: returns the # of columns in row ‘i’

2-Dimensional Array 2-D representation double[ ][ ] Salary= new double[10][6]; Department 10, Employee 1: Salary[9][0] Salary information of 10 departments each having 6 employees

Initialize 2-D Arrays You can initialize by nesting of loops final int MAX_ROW = 25; final int MAX_COL = 1000; double[][] experData = new double[MAX_ROW][MAX_COL]; int i,j; for (i = 0; i < MAX_ROW; i ++) { for (j = 0; j < MAX_COL; j ++) { experData [i][j] = 0.0; } Alternate way: –double [][] scores={{5.3, 6.9, 8.8, 1.7}, {2.2, 9.4, 1.6, 7.5} }; 2 rows, 4 columns

Ragged Arrays Since a two-dimensional array in Java is an array of arrays, each row can have a different number of elements (columns). Arrays in which rows have different numbers of elements are called ragged arrays. Example int[][] b = new int[3][]; b[0] = new int[5]; // array of 5 elements b[1] = new int[7];// array of 7 elements b[2] = new int[4]; // array of 4 elements

Quiz Task : print all the system.out.println statements. public class arrayTest { public static void main(String[] args) { String[] names={"Hemant", "David", "Wini","Kaku"}; System.out.println("length of the array:" + names.length); for(int i=0;i<names.length;i++) { System.out.println(names[i]); } } }

Review: Exam 1 – Q5 Q5. Given the following code: double a = 1/3; double b = 1/3; double c = 1/3; double sum = a + b + c; The value of variable sum is: (a) (b) 0.0 (c) (d) 1.0 Q5. Modified Version. Given the following code: double a = 1/3; double b = 1/3; double c = 1/3; double sum = a + b + c; The value of variable sum is: –All integers: 0 –All floats 0.0 –All doubles: 0.0

Review: Exam 1 – Q8 What is the output of the following program fragment? String s1 = "How are you?"; String s2 = "Who are you?"; int compareVal = (s1.substring(3)).compareTo(s2.substring(3)) > 0? 1:0; switch (compareVal) { case 1: System.out.println(s1);break; case 0: System.out.println(s2); } (a) w are you? (b) How are you? Who are you? (c) Who are you? (d) How are you? Solution: s1.substring(3)--> are you? s2.substring(3)--> are you? s1.substring(3)).compareTo(s2.substring(3)-->0 Who are you? beginning index till the end of string

Review: Exam 1 – Q11 Which of the following are true regarding String comparison (assume s1 and s2 have been declared as String)? I. The operator "==" and the method equals always return the same result II. The compareTo method should be used to compare two strings instead of the operators ">" and "<" III. s1.compareTo(s2) returns a negative number if s1 comes after s2 lexicographically (a) I and II only (b) I, II and III (c) II only (d) II and III only

Review: Exam 1 – Program 1 (20 points) Write a program that prompts for a number n which indicates the number of columns and uses the number to display the following pattern (depicting n = 6 where the maximum number of X is n. X XX XXX XXXX XXXXX XXXXXX XXXXX XXXX XXX XX X

Review: Exam 1 – Program 2 Write a program that converts a user-defined integer n to base k where k is another user defined integer. Your program should first prompt for the integer n which will be converted, then prompt for the base value k. Your program should also write the result as a string in the following format: n = result base k

Review: Exam 1 – Program 3 Nicomachus’s Theorem states that the nth cubic number n3 is a sum of n consecutive odd umbers. For example: 13 = 1 23 = = = The first term in each sequence is n(n 1) + 1. Write code for: private void initialize() public int byMultiply() public int byAdd()