Download Part 1

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Chapter 6
Arrays
Copyright © 2010 Pearson Addison-Wesley.
All rights reserved.
Introduction to Arrays
• An array is a data structure used to process a collection
of data that is all of the same type
– It has a part that does not change: the name of the array
– It has a part that can change: an integer in square brackets
– For example, given five scores:
score[0], score[1], score[2], score[3], score[4]
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
6-2
Arrays
• An array is an ordered list of values
Entire array has
A single name
scores
Each value has
A numeric index
[0]
79
[1]
[2]
[3]
62
98
57
• An array of size N is indexed from zero to N-1
• This array holds 4 values that are indexed from 0 to 3
Declaring an Array
• Defining an array
Type [ ] name
• Where:
– Type specifies the kind of values the array stores
– the brackets [ ] indicate this is an array
– name is the handle to access the array
Syntax
• Forms
ElementType [] arrayName;
ElementType [] arrayName = new ElementType [size];
ElementType [] arrayName = array-literal;
• Where:
– ElementType is any type
– arrayName is the handle for the array
– array-literal is a list of literals enclosed in curly braces {
}
Declaring an Array
• The scores array could be declared as follows:
double [] scores = new double [4];
• The above statement will:
– allocate block of memory to hold 4 doubles
– initialize block with zeros
– create a handle or a pointer or a reference called scores
– store address of the block in scores
scores
[0]
0.0
Handle
Block
[1]
[2]
[3]
0.0
0.0
0.0
Declaring an Array
double[] my List = new double[10];
my List
reference
my List[0]
my List[1]
my List[2]
my List[3]
my List[4]
my List[5]
my List[6]
my List[7]
my List[8]
my List[9]
An Array of 10
Elements
of type double
Declaring Arrays
• Some examples of array declarations:
float[] prices = new float[150];
boolean[] flags;
flags = new boolean[20];
char[] codes = new char[50];
Initializer Lists
• An initializer list can be used to instantiate and
initialize an array in one step
• The values are delimited by braces and separated by
commas
• Examples:
int[] scores = {98, 76, 54, 83, 87, 65, 99, 66};
char[] letterGrades = {'A', 'B', 'C', 'D', ’F'};
Initializer Lists: Example
• Consider the following 4 student names
String [] STUDENTS = {"Aref", "Ali", "Emad", "Sami"};
• Note results:
STUDENTS
[0]
Aref
[1]
Ali
[2]
Emad
[3]
Sami
Array elements are handles for String values
Initializing Arrays
• Another way of initializing an array is by using a for loop
double[] reading = new double[100];
int index;
for (index = 0; index < reading.length; index++)
reading[index] = 42.0;
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
6-11
Processing Array Elements
• Access individual elements of an array using:
– the name of the array
– a number (index or subscript) that tells which of
the element of the array
• What value is stored in scores[2]?
scores
[0]
79
[1]
[2]
[3]
62
98
57
Arrays
• An array element can be assigned a value, printed, or used in
a calculation:
scores[2] = 87;
scores[first] = scores[first] + 2;
Avg = (scores[0] + scores[1])/2;
System.out.println (" Max = " + scores[3]);
Processing Arrays
public class arr1 {
public static void main(String[] args) {
double [ ] a=new double[10];
for(int i=0;i<10;i++)
{
a[i]=i*2.2;
System.out.println(a[i]);
}
}
The length Instance Variable
• An array is considered to be an object
• Since other objects can have instance variables, so can
arrays
• Every array has exactly one instance variable named
length
– When an array is created, the instance variable length is
automatically set equal to its size
– The value of length cannot be changed (other than by
creating an entirely new array with new)
double[] score = new double[5];
– Given score above, score.length has a value of 5
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
6-15
class arr2{
public static void main(String args[]){
int num[ ] = {4, 6, 2, 3, 9, 5, 7, 2, 4, 7};
for(int i=0; i<num.length; i++)
System.out.print(num[i]+ "\t ");
System.out.println( );
for(int i=num.length-1; i>=0; i--)
System.out.print(num[i]+ "\t ");
}
}
import java.util.*;
class array5{
public static void main(String args[]){
double [ ] marks = new double[6];
String [ ] names = new String[6];
Scanner kb=new Scanner(System.in)
for(int i=0; i<6; i++){
System.out.print("Enter Student Name:");
names[i]=kb.next();
System.out.print("Enter Mark:");
marks[i]=kb.nextDouble();
}
for(int i=0; i<6; i++){
if(marks[i]>=60)
System.out.println(names[i]);
}
}
}
Find the smallest number and index of
this number
public class Minimum{
public static void main(String[] args){
int[ ] a={13,17,11,9,89,5,90};
int Index;
int min = a[0];
for(int i=1;i<a.length;i++){
if(a[i]<min){
min=a[i];
Index=i;
}
System.out.println("Minimum Number is "+min);
System.out.println("The index of number is" +Index);
}
}
Bounds Checking
• Once an array is created, it has a fixed size
• That is, the index value must be in bounds (0 to N-1)
• For example, if the array scores can hold 100 values, it can be indexed
using only the numbers 0 to 99
• Often for loop is used to process array. It’s common to introduce off-byone errors when using arrays
problem
for (int index=0; index <= 100; index++)
scores[index] = index*50 + 10;
The Assignment Operation
Java provides a few operations to use with arrays, including assignment
• Consider:
int [] alist = { 1, 12, 15, 7};
int [] blist;
blist = alist;
• We have one array with two names
• So if I were to do something like:
blist[1] = 19;
• What would be the output for the following statements?
System.out.println(alist[1]);
System.out.println(blist[1]);
Array Cloning
• To actually create another array with its own values, Java
provides the .clone() method
int [] alist = {1, 12, 15, 7};
int [] blist;
blist = alist.clone();
• Now there are two separate lists of numbers, one with handle
alist, the other with handle blist
Array Equality
• We must write our own method to compare the arrays
– they both must have the same length
– then use a for( ) loop to compare element by element for equality
boolean As
areEqual
true;pair of elements is found not
soon as= one
if (list1.length !=equal,
list2.length)
the arrays are not equal
areEqual = false;
else {
for (int i = 0; i < list1.length; i++)
if (list1[i] != list2[i]) {
areEqual = false;
break;
}
}
if(areEqual)
System.out.println(“They are equal”);
else
System.out.println(“They are NOT equal”);
Array Equality
• Java has an equals() method for classes
if (a1.equals(a2)) …
• If a1 and a2 are arrays, the equals() method just looks at
the addresses the handles point to
• They could be pointing to different addresses but the contents
of the array still be equal
The "for each" Loop
• there is a new kind of for loop, first available in Java 5.0,
called a for-each loop or enhanced for loop
• The general syntax for a for-each loop statement used with an
array is
for (ArrayType VariableName : ArrayName)
Statement
• The above for-each line should be read as "for each
VariableName in ArrayName do the following:”
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
6-24
The "For-Each" Loop
for (int i = 0; i < a.length; i++)
a[i] = 0.0;
– Can be changed to:
for (double element : a)
element = 0.0;
for (int i = 0; i<grades.length; i++
total += grades[i];
)
// uses Java 5.0 for each looping
for (float grade : grades) {
total += grade;
}
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
6-25
import java.util.*;
public class Sorting{
public static void main(String[] args) {
String[] data ={"ziad","ahmed", "asaad", “Salim”};
Arrays.sort(data);
System.out.println (“Array in Ascending Order”);
for(int i=0;i<data.length;i++)
System.out.println(data[i]);
System.out.println (“Array in Descending Order”);
for(int i=data.length-1;i>=0;i--)
System.out.println (data[i]);
}
}
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
6-26
Enumerated Types
• Starting with version 5.0, Java permits enumerated types
– An enumerated type is a type in which all the values are given in a
(typically) short list
• The definition of an enumerated type is normally placed
outside of all methods in the same place that named
constants are defined:
enum TypeName {VALUE_1, VALUE_2, …, VALUE_N};
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
6-27
Enumerated Types
• An enumerated type is a type in which all the values are given
in a (typically) short list
enum TypeName {VALUE_1, VALUE_2, …, VALUE_N};
Example:
enum WeekDays {MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
FRODAY};
6-28
Enumerated Types Example
• Given the following definition of an enumerated type:
enum WorkDay {MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY};
• A variable of this type can be declared as follows:
WorkDay meetingDay, availableDay;
• The value of a variable of this type can be set to one
of the values listed in the definition of the type, or
else to the special value null:
meetingDay = WorkDay.THURSDAY;
availableDay = null;
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
6-29
An Enumerated Type
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
6-30
Exercise
• Write a program that reads a sequence of 10 integers
into an array and then computes the alternating sum of
all elements in the array.
– For example if the array is : 1 4 9 16 9 7 4 9 11
then it computes : 1 – 4 + 9 – 16 + 9 – 7 + 4 – 9 + 11 = -2
Example: Table of Student Grades
• Imagine a class of 7 students that have a quiz grades for 5 weeks.
These grades can be stored in a table form.
• A particular cell of the table is identified by student number and
week number. For example:
• The grade for student 0 in week 1 is 42
Student
• The grade for student 3 in week 4 is 93
• The grade for student 6 in week 2 is 78
Week
0
1
2
3
4
0
99
42
74
83
100
1
90
91
72
88
95
2
88
61
74
89
96
3
61
89
82
98
93
4
93
73
75
78
99
5
50
65
92
87
94
6
43
98
78
56
99
2-D Arrays in Java
• In Java, a table may be implemented as a 2-D array.
• Each slot of the array is specified with a row and column .
• Suppose that gradeTable is a 2-D array then the syntax to
specify a particular slot should be gradeTable[row][col]
• For example
Student
Week
0
1
2
3
4
0
99
42
74
83
100
1
90
91
72
88
95
2
88
61
74
89
96
– gradeTable[3][4] is 93
3
61
89
82
98
93
4
93
73
75
78
99
– gradeTable[6][2] is 78
5
50
65
92
87
94
6
43
98
78
56
99
– gradeTable[0][1] is 42
2-D Arrays in Java
• The subscripted variables of a 2-D array can be used in assignment statements
and arithmetic expressions just like any variable:
gradeTable[ 0 ][ 1 ] = 33 ; // puts a 33 into row 0 column 1.
gradeTable[ 3 ][ 4 ]++; //increments the value at row 3 column 4.
int value = (gradeTable[ 6 ][ 2 ] + 2)/2;//puts 40 into value
Student
• Write a Java statement that puts a
zero into row 5 column 3.
gradeTable[ 5 ][ 3 ] = 0
Week
0
1
2
3
4
0
99
33
74
83
100
1
90
91
72
88
95
2
88
61
74
89
96
3
61
89
82
98
94
4
93
73
75
78
99
5
50
65
92
87
94
6
43
98
78
56
99
2-D Array Declaration
• In Java, a 2-D array is an object.
• To declare a reference variable myArray to a 2-D array of int:
int[][] myArray;
• To create an array object of 3 rows and 5 columns, and put the reference in
myArray, we write
int[][] myArray = new int[3][5];
• All the elements of myArray are initialized to zero.
• We can create the above array by using the initializer list:
int[][] myArray = {{0,1,2,3,4}, {2,3,5,9,10}, {2,6,8,1,6}};
Different Numbers of Elements per Row
• In Java, each row of a 2-D array may have a different number of
elements. In the following example, the array A has
– 3 elements in its first row,
– 2 in its second row,
– and 5 in its last row.
int[ ][ ] A = {{ 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 }};
Length of a 2-D Array
•
The length of a 2-D array is the number of rows it has.
– So the row index (number) is from 0 to length-1.
•
As each row in a 2-D array is like a 1-D array, we can refer to an entire row by
specifying just the row index, e.g., A[0] means row # 0
•
The length of a row is the number of columns in the row.
•
As each row of a 2-D array can have a different number of columns, so each row has
its own length.
int[][] A = { { 1, 9, 4 },
System.out.println("Length
System.out.println("Length
System.out.println("Length
System.out.println("Length
{ 0, 2}, { 0, 1, 2, 3, 4 } };
of array is: " + A.length );
of row[0] is: " + A[0].length );
of row[1] is: " + A[1].length );
of row[2] is: " + A[2].length );
Two-Dimensional Array as an Array of Arrays (Part 1 of 2)
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
6-38
Two-Dimensional Array as an Array of Arrays (Part 2 of 2)
Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
6-39