Arrays (Deitel chapter 7)

Similar documents
Chapter 6 Arrays and Strings Prentice Hall, Inc. All rights reserved.

Arrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type

Outline. 7.1 Introduction. 7.2 Arrays. 7.2 Arrays

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

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

Instructor: Eng.Omar Al-Nahal

Methods (Deitel chapter 6)

Methods (Deitel chapter 6)

Control Statements. Musa M. Ameen Computer Engineering Dept.

Object Oriented Programming. Java-Lecture 6 - Arrays

Arrays Pearson Education, Inc. All rights reserved.

Programming for Engineers Arrays

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

Chapter 9 Introduction to Arrays. Fundamentals of Java

Chapter 6 - Methods Prentice Hall. All rights reserved.

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

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

Part 8 Methods. scope of declarations method overriding method overloading recursions

The first applet we shall build will ask the user how many times the die is to be tossed. The request is made by utilizing a JoptionPane input form:

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

Chapter 4 Control Structures: Part 2

Here, type declares the base type of the array, which is the type of each element in the array size defines how many elements the array will hold

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

Multiple-Subscripted Arrays

Class C{ int a; } what variables below are objects : a. C c; b. String str; c. Scanner scanner; d. int num; e. float f;

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

C: How to Program. Week /Apr/23

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

CHAPTER 3 ARRAYS. Dr. Shady Yehia Elmashad

More non-primitive types Lesson 06

C++ PROGRAMMING SKILLS Part 4: Arrays

Control Structures (Deitel chapter 4,5)

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

Chapter 5 Control Structures: Part 2

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

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

Chapter 12 Two-Dimensional Arrays

Fundamentals of Programming Session 15

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

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

Array. Prepared By - Rifat Shahriyar

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

Chapter 6. Arrays. Copyright 2007 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

array Indexed same type

Chapter 7 Multidimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Course PJL. Arithmetic Operations

C Arrays Pearson Education, Inc. All rights reserved.

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

Lecture 04 FUNCTIONS AND ARRAYS

Arrays. Defining arrays, declaration and initialization of arrays. Designed by Parul Khurana, LIECA.

Computer Programming: C++

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

Arrays. Eng. Mohammed Abdualal

Outline Introduction Arrays Declaring Arrays Examples Using Arrays Passing Arrays to Functions Sorting Arrays

ECE 30 Introduction to Computer Engineering

JAVA- PROGRAMMING CH2-EX1

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

Chapter 6: Using Arrays

Arrays Chapter 6 Chapter 6 1

Chapter 8 Multi-Dimensional Arrays

Arrays. Theoretical Part. Contents. Keywords. Programming with Java module 3

Tutorial about Arrays

Chapter 7 : Arrays (pp )

Array. Arrays. Declaring Arrays. Using Arrays

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

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Chapter 7 Multidimensional Arrays

Sun ONE Integrated Development Environment

Arrays. Arrays: Declaration and Instantiation. Array: An Array of Simple Values

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Generics Pearson Education, Inc. All rights reserved.

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

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

TOPICS TO COVER:-- Array declaration and use.

V2 3/5/2012. Programming in C. Introduction to Arrays. 111 Ch 07 A 1. Introduction to Arrays

CS360 Lecture 5 Object-Oriented Concepts

Arrays. int Data [8] [0] [1] [2] [3] [4] [5] [6] [7]

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

CMSC131. Arrays: The Concept

Arrays and Pointers (part 1)

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

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

An array can hold values of any type. The entire collection shares a single name

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

Arrays and Applications

by Pearson Education, Inc. All Rights Reserved. 2

Chapter 11 - JavaScript: Arrays

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Introduction to Computer Science Midterm 3 Fall, Points

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

Chapter 7: Arrays and the ArrayList Class

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Example: Computing prime numbers

Chapter 4. Section 4.5 Initialization of Arrays. CS 50 Hathairat Rattanasook

Maltepe University Computer Engineering Department. BİL 133 Algorithms and Programming. Chapter 8: Arrays

Transcription:

Arrays (Deitel chapter 7)

Plan Arrays Declaring and Creating Arrays Examples Using Arrays References and Reference Parameters Passing Arrays to Methods Sorting Arrays Searching Arrays: Linear Search and Binary Search Multidimensional Arrays

Name of array (note that all elements of this array have the same name, c) Index (or subscript) of the element in array c c[ 0 ] c[ 1 ] c[ 2 ] c[ 3 ] c[ 4 ] c[ 5 ] c[ 6 ] c[ 7 ] c[ 8 ] c[ 9 ] c[ 10 ] c[ 11 ] -45 6 0 72 1543-89 0 62-3 1 6453 78 Fig. 7.1 A 12-element array.

Arrays Index Also called subscript Position number in square brackets Must be positive integer or integer expression a = 5; b = 6; c[ a + b ] += 2; Adds 2 to c[ 11 ]

Arrays (cont.) Examine array c c is the array name c.length accesses array c s length c has 12 elements ( c[0], c[1], c[11] ) The value of c[0] is 45

Declaring and Creating Arrays Declaring and Creating arrays Arrays are objects that occupy memory Created dynamically with keyword new int c[] = new int[ 12 ]; Equivalent to int c[]; // declare array variable c = new int[ 12 ]; // create array We can create arrays of objects too String b[] = new String[ 100 ];

1 // Fig. 7.2: InitArray.java 2 // Creating an array. 3 import javax.swing.*; 4 5 public class InitArray { 6 7 public static void main( String args[] ) 8 { 9 int array[]; // declare reference to an array 10 11 array = new int[ 10 ]; // create array 12 13 String output = "Index\tValue\n"; 14 15 // append each array element's value to String output 16 for ( int counter = 0; counter < array.length; counter++ ) 17 output += counter + "\t" + array[ counter ] + "\n"; 18 19 JTextArea outputarea = new JTextArea(); 20 outputarea.settext( output ); 21 22 JOptionPane.showMessageDialog( null, outputarea, 23 "Initializing an Array of int Values", 24 JOptionPane.INFORMATION_MESSAGE ); 25 26 System.exit( 0 ); 27 28 } // end main 29 30 } // end class InitArray Outline Create 10 ints for array; each Declare array int is as initialized an to 0 by default InitArray.java array of ints Line 9 array.length returns Declare array as an length of array array of ints array[counter] returns int associated with index in array Line 11 Create 10 ints for array; each int is initialized to 0 by default Line 16 array.length returns length of array Line 17 array[counter] returns int associated with index in array

Outline InitArray.java Each int is initialized to 0 by default Each int is initialized to 0 by default

Examples Using Arrays Using an array initializer Use initializer list Items enclosed in braces ({}) Items in list separated by commas int n[] = { 10, 20, 30, 40, 50 }; Creates a five-element array Index values of 0, 1, 2, 3, 4 Do not need keyword new

1 // Fig. 7.3: InitArray.java 2 // Initializing an array with a declaration. Declare array as an 3 import javax.swing.*; array of ints 4 5 public class InitArray { 6 7 public static void main( String args[] ) 8 { 9 // array initializer specifies number of elements and 10 // value for each element 11 int array[] = { 32, 27, 64, 18, 95, 14, 90, 70, 60, 37 }; 12 13 String output = "Index\tValue\n"; 14 15 // append each array element's value to String output 16 for ( int counter = 0; counter < array.length; counter++ ) 17 output += counter + "\t" + array[ counter ] + "\n"; 18 19 JTextArea outputarea = new JTextArea(); 20 outputarea.settext( output ); 21 22 JOptionPane.showMessageDialog( null, outputarea, 23 "Initializing an Array with a Declaration", 24 JOptionPane.INFORMATION_MESSAGE ); 25 26 System.exit( 0 ); 27 28 } // end main 29 30 } // end class InitArray Outline InitArray.java Compiler uses initializer Line list 11 to allocate arraydeclare array as an array of ints Line 11 Compiler uses initializer list to allocate array

Outline InitArray.java Each array element corresponds to element in initializer list Each array element corresponds to element in initializer list

Examples Using Arrays Summing the elements of an array Array elements can represent a series of values We can sum these values

1 // Fig. 7.5: SumArray.java 2 // Total the values of the elements of an Declare array. array with 3 import javax.swing.*; initializer list 4 5 public class SumArray { 6 7 public static void main( String args[] ) 8 { 9 int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 10 int total = 0; 11 12 // add each element's value to total 13 for ( int counter = 0; counter < array.length; counter++ ) 14 total += array[ counter ]; 15 16 JOptionPane.showMessageDialog( null, 17 "Total of array elements: " + total, 18 "Sum the Elements of an Array", 19 JOptionPane.INFORMATION_MESSAGE ); 20 21 System.exit( 0 ); 22 23 } // end main 24 25 } // end class SumArray Sum all array values Outline SumArray.java Line 9 Declare array with initializer list Lines 13-14 Sum all array values

Examples Using Arrays (Cont.) Some additional points When looping through an array Index should never go below 0 Index should be less than total number of array elements When invalid array reference occurs Java generates ArrayIndexOutOfBoundsException Exception handling

References and Reference Parameters Two ways to pass arguments to methods Pass-by-value Copy of argument s value is passed to called method In Java, every primitive is pass-by-value Pass-by-reference Caller gives called method direct access to caller s data Called method can manipulate this data Improved performance over pass-by-value In Java, every object is pass-by-reference In Java, arrays are objects Therefore, arrays are passed to methods by reference

Passing Arrays to Methods To pass array argument to a method Specify array name without brackets Array hourlytemperatures is declared as int hourlytemperatures = new int[ 24 ]; The method call modifyarray( hourlytemperatures ); Passes array hourlytemperatures to method modifyarray

1 // Fig. 7.9: PassArray.java 2 // Passing arrays and individual array elements to methods. 3 import java.awt.container; 4 import javax.swing.*; 5 6 public class PassArray extends JApplet { 7 8 // initialize applet 9 public void init() 10 { 11 JTextArea outputarea = new JTextArea(); 12 Container container = getcontentpane(); 13 container.add( outputarea ); 14 15 int array[] = { 1, 2, 3, 4, 5 }; 16 Declare 5-int array with initializer list 17 String output = "Effects of passing entire array by reference:\n" + 18 "The values of the original array are:\n"; 19 20 // append original array elements to String output 21 for ( int counter = 0; counter < array.length; counter++ ) 22 output += " " + array[ counter ]; 23 24 modifyarray( array ); // array passed by reference 25 26 output += "\n\nthe values of the modified array are:\n"; 27 28 // append modified array elements to String output 29 for ( int counter = 0; counter < array.length; counter++ ) 30 output += " " + array[ counter ]; 31 32 output += "\n\neffects of passing array element by value:\n" + 33 "array[3] before modifyelement: " + array[ 3 ]; 34 Outline PassArray.java Line 15 Declare 5-int array with initializer list Pass array by reference to Line 24 method modifyarray Pass array by reference to method modifyarray

35 modifyelement( array[ 3 ] ); // attempt to modify array[ 3 ] 36 Pass array[3] by value to 37 output += "\narray[3] after modifyelement: " + array[ 3 ]; 38 outputarea.settext( output ); method modifyelement 39 Method modifyarray 40 } // end method init 41 42 // multiply each element of an array by 2 43 public void modifyarray( int array2[] ) 44 { 45 for ( int counter = 0; counter < array2.length; counter++ ) 46 array2[ counter ] *= 2; 47 } 48 49 // multiply argument by 2 50 public void modifyelement( int element ) 51 { 52 element *= 2; 53 } 54 55 } // end class PassArray manipulates the array directly Outline PassArray.java Line 35 Pass array[3] by value to method modifyelement Method modifyelement manipulates a primitive s copylines 43-47 Method modifyarray manipulates the array The original primitive is left unmodified directly The object passed-by-reference is modified Lines 50-53 Method modifyelement manipulates a primitive s copy The primitive passed-by-value is unmodified Lines 52 The original primitive is left unmodified

Multidimensional Arrays Multidimensional arrays Tables with rows and columns Two-dimensional array Declaring two-dimensional array b[2][2] int b[][] = { { 1, 2 }, { 3, 4 } }; 1 and 2 initialize b[0][0] and b[0][1] 3 and 4 initialize b[1][0] and b[1][1] int b[][] = { { 1, 2 }, { 3, 4, 5 } }; row 0 contains elements 1 and 2 row 1 contains elements 3, 4 and 5

Multidimensional Arrays (Cont.) Creating multidimensional arrays Can be allocated dynamically 3-by-4 array int b[][]; b = new int[ 3 ][ 4 ]; Rows can have different number of columns int b[][]; b = new int[ 2 ][ ]; // allocate rows b[ 0 ] = new int[ 5 ]; // allocate row 0 b[ 1 ] = new int[ 3 ]; // allocate row 1

Column 0 Column 1 Column 2 Column 3 Row 0 Row 1 Row 2 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ] a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ] a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ] Column index Row index Array name Two-dimensional array with three rows and four columns.

1 // Fig. 7.14: InitArray.java 2 // Initializing two-dimensional arrays. 3 import java.awt.container; 4 import javax.swing.*; 5 6 public class InitArray extends JApplet { 7 JTextArea outputarea; 8 9 // set up GUI and initialize applet 10 public void init() 11 { 12 outputarea = new JTextArea(); 13 Container container = getcontentpane(); 14 container.add( outputarea ); 15 16 int array1[][] = { { 1, 2, 3 }, { 4, 5, 6 } }; 17 int array2[][] = { { 1, 2 }, { 3 }, { 4, 5, 6 } }; 18 19 outputarea.settext( "Values in array1 by row are\n" ); 20 buildoutput( array1 ); 21 22 outputarea.append( "\nvalues in array2 by row are\n" ); 23 buildoutput( array2 ); 24 25 } // end method init 26 Outline Declare array1 with six InitArray.java initializers in two sublists Declare array2 with six initializers in three sublists Line 16 Declare array1 with six initializers in two sublists Line 17 Declare array2 with six initializers in three sublists

27 // append rows and columns of an array to outputarea 28 public void buildoutput( int array[][] ) 29 { 30 // loop through array's rows 31 for ( int row = 0; row < array.length; row++ ) { 32 33 // loop through columns of current row 34 for ( int column = 0; column < array[ row ].length; column++ ) 35 outputarea.append( array[ row ][ column ] + " " ); 36 37 outputarea.append( "\n" ); 38 } 39 40 } // end method buildoutput 41 42 } // end class InitArray Outline array[row].length returns number of columns associated with row subscript InitArray.java Use double-bracket notation to access two-dimensional array values Line 34 array[row].lengt h returns number of columns associated with row subscript Line 35 Use double-bracket notation to access twodimensional array values

1 // Fig. 7.15: DoubleArray.java 2 // Two-dimensional array example. 3 import java.awt.*; 4 import javax.swing.*; 5 6 public class DoubleArray extends JApplet { 7 int grades[][] = { { 77, 68, 86, 73 }, 8 { 96, 87, 89, 81 }, 9 { 70, 90, 86, 81 } }; 10 11 int students, exams; Each row represents a student; each column represents an exam grade 12 String output; 13 JTextArea outputarea; 14 15 // initialize fields 16 public void init() 17 { 18 students = grades.length; // number of students 19 exams = grades[ 0 ].length; // number of exams 20 Outline Declare grades as 3-by-4 array DoubleArray.java Lines 7-9 Declare grades as 3- by-4 array Lines 7-9 Each row represents a student; each column represents an exam grade Lines 31-32 Determine minimum and maximum for all student