0% found this document useful (0 votes)
38 views

CSE215 A5 Arrays

Arrays are data structures that store multiple values of the same type. An array is declared with a variable name and type, and memory is allocated for it when it is instantiated with a size. Individual elements in an array are accessed via indexes that represent their position. Common array operations include initializing values, accessing elements, summing values, and finding minimums/maximums using loops.

Uploaded by

wasik mahir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

CSE215 A5 Arrays

Arrays are data structures that store multiple values of the same type. An array is declared with a variable name and type, and memory is allocated for it when it is instantiated with a size. Individual elements in an array are accessed via indexes that represent their position. Common array operations include initializing values, accessing elements, summing values, and finding minimums/maximums using loops.

Uploaded by

wasik mahir
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

Chapter 6 Arrays

Read one hundred numbers, compute their


average, and find out how many numbers are
above the average.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 1
rights reserved. 0132130807
Introducing Arrays
Array is a data structure that represents a collection of the
same types of data.
double[] myList = new double[10];

myList reference
myList[0] 5.6
myList[1] 4.5
Array reference myList[2] 3.3
variable
myList[3] 13.2

myList[4] 4
Array element at
myList[5] 34.33 Element value
index 5
myList[6] 34

myList[7] 45.45

myList[8] 99.993

myList[9] 11123

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 2
rights reserved. 0132130807
Declaring Array Variables

• datatype[] arrayRefVar;
Example:
double[] myList;

• datatype arrayRefVar[]; // This style is


allowed, but not preferred
Example:
double myList[];

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 3
rights reserved. 0132130807
Creating Arrays

arrayRefVar = new datatype[arraySize];

Example:
myList = new double[10];

myList[0] references the first element in the array.


myList[9] references the last element in the array.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 4
rights reserved. 0132130807
Declaring and Creating
in One Step

• datatype[] arrayRefVar = new


datatype[arraySize];
double[] myList = new double[10];

• datatype arrayRefVar[] = new


datatype[arraySize];
double myList[] = new double[10];

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 5
rights reserved. 0132130807
The Length of an Array

Once an array is created, its size is fixed. It cannot be


changed. You can find its size using
arrayRefVar.length

For example,

myList.length returns 10

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 6
rights reserved. 0132130807
Default Values
When an array is created, its elements are
assigned the default value of

0 for the numeric primitive data types,


'\u0000' for char types, and
false for boolean types.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 7
rights reserved. 0132130807
Indexed Variables
The array elements are accessed through the index.
The array indices are 0-based, i.e., it starts from 0 to
arrayRefVar.length-1. In the example in Figure 6.1,
myList holds ten double values and the indices are
from 0 to 9.

Each element in the array is represented using the


following syntax, known as an indexed variable:

arrayRefVar[index];

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 8
rights reserved. 0132130807
Using Indexed Variables
After an array is created, an indexed variable can
be used in the same way as a regular variable.
For example, the following code adds the value
in myList[0] and myList[1] to myList[2].

myList[2] = myList[0] + myList[1];

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 9
rights reserved. 0132130807
Array Initializers

•Declaring, creating, initializing in one step:


double[] myList = {1.9, 2.9, 3.4, 3.5};

This shorthand syntax must be in one


statement.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 10
rights reserved. 0132130807
Declaring, creating, initializing Using the
Shorthand Notation
double[] myList = {1.9, 2.9, 3.4, 3.5};
This shorthand notation is equivalent to the following statements:
double[] myList = new double[4];
myList[0] = 1.9;
myList[1] = 2.9;
myList[2] = 3.4;
myList[3] = 3.5;

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 11
rights reserved. 0132130807
CAUTION
Using the shorthand notation, you
have to declare, create, and initialize
the array all in one statement.
Splitting it would cause a syntax
error. For example, the following is
wrong:
double[] myList;

myList = {1.9, 2.9, 3.4, 3.5};

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 12
rights reserved. 0132130807
Processing Arrays

See the examples in the text.


1. (Initializing arrays with input values)
2. (Initializing arrays with random values)
3. (Printing arrays)
4. (Summing all elements)
5. (Finding the largest element)
6. (Finding the smallest index of the largest element)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 13
rights reserved. 0132130807
Initializing arrays with input values

java.util.Scanner input = new java.util.Scanner(System.in);


System.out.print("Enter " + myList.length + " values: ");
for (int i = 0; i < myList.length; i++)
myList[i] = input.nextDouble();

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 14
rights reserved. 0132130807
Initializing arrays with random values

for (int i = 0; i < myList.length; i++) {


myList[i] = Math.random() * 100;
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 15
rights reserved. 0132130807
Printing arrays

for (int i = 0; i < myList.length; i++) {


System.out.print(myList[i] + " ");
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 16
rights reserved. 0132130807
Summing all elements

double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 17
rights reserved. 0132130807
Finding the largest element

double max = myList[0];


for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 18
rights reserved. 0132130807
Enhanced for Loop (for-each loop)
JDK 1.5 introduced a new for loop that enables you to traverse the complete array
sequentially without using an index variable. For example, the following code
displays all elements in the array myList:

for (double value: myList)


System.out.println(value);

In general, the syntax is

for (elementType value: arrayRefVar) {


// Process the value
}

You still have to use an index variable if you wish to traverse the array in a
different order or change the elements in the array.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 19
rights reserved. 0132130807
Copying Arrays
Often, in a program, you need to duplicate an array or a part of an
array. In such cases you could attempt to use the assignment
statement (=), as follows:

list2 = list1;
Before the assignment After the assignment
list2 = list1; list2 = list1;

list1 list1
Contents Contents
of list1 of list1

list2 list2
Contents Contents
of list2 of list2
Garbage

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 20
rights reserved. 0132130807
Copying Arrays

Using a loop:
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new
int[sourceArray.length];

for (int i = 0; i < sourceArrays.length; i++)


targetArray[i] = sourceArray[i];

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 21
rights reserved. 0132130807
The arraycopy Utility

arraycopy(sourceArray, src_pos,
targetArray, tar_pos, length);

Example:
System.arraycopy(sourceArray, 0,
targetArray, 0, sourceArray.length);

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 22
rights reserved. 0132130807
The Arrays.sort Method
Since sorting is frequently used in programming, Java provides several
overloaded sort methods for sorting an array of int, double, char, short,
long, and float in the java.util.Arrays class. For example, the following
code sorts an array of numbers and an array of characters.

double[] numbers = {6.0, 4.4, 1.9, 2.9, 3.4, 3.5};


java.util.Arrays.sort(numbers);

char[] chars = {'a', 'A', '4', 'F', 'D', 'P'};


java.util.Arrays.sort(chars);

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 23
rights reserved. 0132130807
Declare/Create Two-dimensional Arrays
// Declare array ref var
dataType[][] refVar;

// Create array and assign its reference to variable


refVar = new dataType[10][10];

// Combine declaration and creation in one statement


dataType[][] refVar = new dataType[10][10];

// Alternative syntax
dataType refVar[][] = new dataType[10][10];

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 24
rights reserved. 0132130807
Declaring Variables of Two-
dimensional Arrays and Creating Two-
dimensional Arrays
int[][] matrix = new int[10][10];
or
int matrix[][] = new int[10][10];
matrix[0][0] = 3;

for (int i = 0; i < matrix.length; i++)


for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = (int)(Math.random() * 1000);

double[][] x;

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 25
rights reserved. 0132130807
Two-dimensional Array Illustration

0 1 2 3 4 0 1 2 3 4 0 1 2
0 0 0 1 2 3

1 1 1 4 5 6

2 2 7 2 7 8 9

3 3 3 10 11 12

4 4 int[][] array = {
{1, 2, 3},
matrix = new int[5][5]; matrix[2][1] = 7; {4, 5, 6},
{7, 8, 9},
{10, 11, 12}
};

matrix.length? 5 array.length? 4
matrix[0].length? 5 array[0].length? 3

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 26
rights reserved. 0132130807
Declaring, Creating, and Initializing Using Shorthand
Notations

You can also use an array initializer to declare, create and


initialize a two-dimensional array. For example,

int[][] array = {
int[][] array = new int[4][3];
{1, 2, 3}, array[0][0] = 1; array[0][1] = 2; array[0][2] = 3;
{4, 5, 6}, Same as array[1][0] = 4; array[1][1] = 5; array[1][2] = 6;
{7, 8, 9}, array[2][0] = 7; array[2][1] = 8; array[2][2] = 9;
{10, 11, 12} array[3][0] = 10; array[3][1] = 11; array[3][2] = 12;
};

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 27
rights reserved. 0132130807
Lengths of Two-dimensional Arrays

int[][] x = new int[3][4];

x
x[0][0] x[0][1] x[0][2] x[0][3] x[0].length is 4
x[0]
x[1] x[1][0] x[1][1] x[1][2] x[1][3] x[1].length is 4

x[2]
x[2][0] x[2][1] x[2][2] x[2][3] x[2].length is 4
x.length is 3

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 28
rights reserved. 0132130807
Lengths of Two-dimensional Arrays, cont.

int[][] array = { array.length


{1, 2, 3}, array[0].length
{4, 5, 6},
array[1].length
{7, 8, 9},
array[2].length
{10, 11, 12}
array[3].length
};

array[4].length ArrayIndexOutOfBoundsException

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 29
rights reserved. 0132130807
Ragged Arrays
Each row in a two-dimensional array is itself an array. So,
the rows can have different lengths. Such an array is
known as a ragged array. For example,
int[][] matrix = {
{1, 2, 3, 4, 5},
matrix.length is 5
{2, 3, 4, 5}, matrix[0].length is 5
{3, 4, 5}, matrix[1].length is 4
{4, 5}, matrix[2].length is 3
matrix[3].length is 2
{5}
matrix[4].length is 1
};

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 30
rights reserved. 0132130807
Ragged Arrays, cont.

int[][] triangleArray = { 1 2 3 4 5
{1, 2, 3, 4, 5},
{2, 3, 4, 5}, 1 2 3 4
{3, 4, 5},
{4, 5}, 1 2 3
{5}
}; 1 2

1 2

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 31
rights reserved. 0132130807
Processing Two-Dimensional Arrays

See the examples in the text.

1. (Initializing arrays with input values)


2. (Printing arrays)
3. (Summing all elements)
4. (Summing all elements by column)
5. (Which row has the largest sum)
6. (Finding the smallest index of the largest element)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 32
rights reserved. 0132130807
Initializing arrays with input values
java.util.Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix.length + " rows and " +
matrix[0].length + " columns: ");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = input.nextInt();
}
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 33
rights reserved. 0132130807
Initializing arrays with random values

for (int row = 0; row < matrix.length; row++) {


for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = (int)(Math.random() * 100);
}
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 34
rights reserved. 0132130807
Printing arrays
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(matrix[row][column] + " ");
}

System.out.println();
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 35
rights reserved. 0132130807
Summing all elements
int total = 0;
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
total += matrix[row][column];
}
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 36
rights reserved. 0132130807
Summing elements by column
for (int column = 0; column < matrix[0].length; column++) {
int total = 0;
for (int row = 0; row < matrix.length; row++)
total += matrix[row][column];
System.out.println("Sum for column " + column + " is "
+ total);
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 37
rights reserved. 0132130807
Multidimensional Arrays
Occasionally, you will need to represent n-dimensional
data structures. In Java, you can create n-dimensional
arrays for any integer n.

The way to declare two-dimensional array variables and


create two-dimensional arrays can be generalized to
declare n-dimensional array variables and create n-
dimensional arrays for n >= 3. For example, the following
syntax declares a three-dimensional array variable scores,
creates an array, and assigns its reference to scores.

double[][][] scores = new double[10][5][2];

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 38
rights reserved. 0132130807

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy