[go: up one dir, main page]

0% found this document useful (0 votes)
23 views45 pages

Chapter 4

Uploaded by

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

Chapter 4

Uploaded by

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

Chapter 4 Single

Dimensional
Arrays
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.
0132130807
Opening
Problem
• Read one hundred numbers, compute their average, and find
out how many
numbers are above the average.
• Defining 100 variables and writing 100 lines to read is not
practical!
• What if there is a way to create a list of 100 items?
• How to access the items or any item of the list?
• Items on the list have positions.
• The first item is on the first position.
• We will create an indexing system.
• We will refer to each position with its index of the list.
• The first element will be at index 0

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 2
0132130807
Introducing
Arrays
• Array is a data structure that represents a collection of the
same types of data.
double[ ] myList = {5.6,4.5, 3.3, 13.2, 4.08,
34.33, 34.0, 45.45, 99.99, 11.23}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 3
0132130807
Declaring Array
Variables
• Use the square brackets [ ] to tell the compiler this is a list not a
single data item.
• To declare an array, use the following syntax datatype[] arrayName;
double[]
• Example:myList;
•datatype arrayRefVar[]; // This style is allowed, but not
preferred
double
Example: myList[];

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 4
0132130807
Creating
Arrays
Index
• arrayName = new
datatype[arraySize]; 0 9
• Example:
myList = new
double[10];
• new reserves 10 positions of the double-
• double[10] type size.
myList[0 references the first element in
• ]
myList[9 the array.
] references the last element in
the array.
Declaring and Creating in
•One Step arrayRefVar = new
datatype[]
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 rights reserved. 5
0132130807
The Length or size of an
Array
• Once an array is created, its size is fixed. It cannot be changed. You can
find its size using
arrayname.length
• For example,
• myList.length;
returns 10

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 6
0132130807
Default Values of array elements

• When an array is created, its elements are assigned the


default value of
– 0 for the numeric primitive data
types, such as int, double
– '\u0000' for char types, and
– False for boolean types. (T or F)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 7
0132130807
Indexed
Variables
• The array elements are accessed through the index.
• The array indices are 0-based, i.e., Array 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:
myList = new
– double[10];
arrayName[index];

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 8
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 rights reserved. 9
0132130807
Array
Initializers
• Declaring, creating, initializing in
one step:
double[] myList = {1.9, 2.9, 3.4,
3.8};
int[] myList = {1, 2, 4, 5, 8,
9};
char[] myList = {‘a’, ‘b’,
‘c’};

• This shorthand syntax must be in one


statement.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 10
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 rights reserved. 11
0132130807
CAUTIO
N
• Using the shorthand notation, you have to declare, create, and
initialize the array all in
one statement. Splitting it would cause a syntax error.

• Fordouble[]
example, the following is wrong:
myList;
myList = {1.9, 2.9, 3.4,
3.5};

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 12
0132130807
WAP in Java to get array size, sum of array elements &
average of array elements
public class Exercise
{
public static void main(String[] args)
{
int[] numbers = new int[] {20, 30, 25, 35, 16, 60, 100};
//calculate sum of all array elements
int sum = 0;
for(int i=0; i < numbers.length; i++). //index i //
sum = sum + numbers[i];
//calculate average value
double average = sum / numbers.length;
System.out.println(”Size of the array elements is : " +numbers.length);
System.out.println("Sum value of the array elements is : " +sum);
System.out.println("Average value of the array elements is : " +average);
}
}
OUTPUT:
Total number of the array elements is : 7
Sum value of the array elements is : 286
Average value of the array elements is : 40.0
Trace Program with Declare array variable values, create an
Arrays array, and assign its reference to
values
public class Test {
public static void main(String[]
args)
int[]{ values = new int[5];
After the array is created
for (int i = 1; i < 5; i++) {
values[i] = i + values[i-1]; 0 0
0
} 1

2 0
values[0] = values[1] + 3 0
values[4]; 4 0

}
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 14
0132130807
Trace Program with i ( =5) < 5 is false. Exit the loop
Arrays
public class Test {
public static void main(String[]
args) { int[] values = new
After the fourth iteration
int[5];
for (int i = 1; i < 5; i++) { 0 0
1
values[i] = i + values[i-1]; 1

2 3
} 3 6

values[0] = values[1] + values[4]; 4 10

}
}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 15
0132130807
Trace Program with i ( =5) < 5 is false. Exit the loop
Arrays
public class Test {
public static void main(String[]
args) { int[] values = new
After the fourth iteration
int[5];
for (int i = 1; i < 5; i++) { 0 11
1
values[i] = i + values[i-1]; 1

2 3
} values[0] = values[1] + 3 6

} values[4]; 4 10

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 16
0132130807
Processing
Arrays
• There are many situations where using arrays is the only way to
solve a problem
• To process the items in stored in the array, you must loop
through the array.
– See the examples in the text to check the followings:
• (Initializing arrays with input values)
• (Initializing arrays with random values)
• (Printing arrays)
• (Sum all elements)
• (Finding the largest element of array)
• (Finding the smallest index of the largest element)
• (Shifting elements of array)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 17
0132130807
Exampl double[] myList = {1.9, 2.9, 3.4,
es 3.5};
//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();

//Initializing arrays with random values


for (int i = 0; i < myList.length; i+
+)
{ myList[i] = Math.random() * 100;
}

//Printing array elements


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 rights reserved. 18
0132130807
Exampl double[] myList = {1.9, 2.9, 3.4,
3.5};
es
//Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i+
+) { total += myList[i];
}

//Finding the largest elements in


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

//Printing array elements


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 rights reserved. 19
0132130807
Shifting
Elements
• Sometimes you need to shift the elements left or right. Here is an example to
shift the elements
one position to the left and fill the last element with the first element:

Actually, this is rotating not shifting!


But, we will use the two
terms interchangeably for
now

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 20
0132130807
Enhanced for Loop (for-each
loop)
double[] myList = {1.9, 2.9, 3.4,
3.5};
• Java(JDK 1.5) supports a convenient for loop, known as a for-each loop or
enhanced for loop,
which enables you to traverse the array sequentially without using an index
variable.
for (int
• For example, the following code displays i elements
all the = 0; i in
< the
myList.length;
array
myList: i++)

• You can read the code as “for each element u in myList do the
following.”
• Note that: the variable, u, must be declared the same type as the
elements in myList.
• In general, the syntax for a for-each loop is

• 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 rights reserved. 21
0132130807
WAP foreach-loop vs for-loop for display the arrray elements
class HelloWorld
{
public static void main(String[] args)
{
int[] numbers = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] num = new int[] {1, 2, 3, 4, 5};

for(int a: numbers) //foreach loop//


{
System.out.println(a);
}

for(int i=0; i<num.length;i++) //for loop// +, -, x, / //


{
System.out.println(num[i]);
}
}
}
WAP by using foreach-loop to display elements of array & find the sum
of elements by for loop.
class HelloWorld
{
public static void main(String[] args)
{
int[] numbers = new int[] {1,2,3,4,5,6,7,8};
for(int a: numbers) //foreach loop// only display the array
elements//
{
System.out.println(a);
}

int sum = 0;
for(int i=0; i < numbers.length; i++) //+,-, *, /, // calulation//
sum = sum + numbers[i];
System.out.println("Sum value of the array elements is : " +sum);
}
}
WAP by using method to find the maximum of elements in an Array
public class MaxInArray
{
public static void main(String[] args)
{
int[] numbers = {3, 5, 1, 8, 4, 2};
int max = findMax(numbers);
System.out.println("The maximum value in the array is: " + max);
}

public static int findMax(int[] array)


{
int max = array[0]; // Assume the first element is the maximum
initially
for (int i = 1; i < array.length; i++)
{
if (array[i] > max) //Greater sign//
{
max = array[i]; // Update max if the current element is greater
}
}
return max;
}
WAP by using method to find the minimum of elements in an Array
public class MinInArray
{
public static void main(String[] args)
{
int[] numbers = {3, 5, 1, 8, 4, 2};
int max = findMin(numbers);
System.out.println("The miimum value in the array is: " + max);
}

public static int findMin(int[] array)


{
int min = array[0]; // Assume the first element is the minimum
initially
for (int i = 1; i < array.length; i++)
{
if (array[i] < min) //Lesser sign//
{
min = array[i]; // Update min if the current element is greater
}
}
return min;
}
WAP to find the sum of array element & find maximum of elements in an Array
class HelloWorld
{ public static void main(String[] args)
{
int[] numbers = new int[] {1,2,3,4,5,6,7,8};
int sum = 0;
for(int i=0; i < numbers.length; i++)
sum = sum + numbers[i];
System.out.println("Sum value of the array elements is : " +sum);
int max = findMax(numbers);
System.out.println("The maximum value in the array is: " + max);
}
public static int findMax(int[] array)
{ int max = array[0];
for (int i = 1; i < array.length; i++)
{ if (array[i] > max)
{ max = array[i];
}
} return max;
}
}
OUTPUT: Sum value of the array elements is : 36
The maximum value in the array is: 8
Copying
Arrays
• Often, in a program, you need to duplicate an array or a part of
an array. list2 =
• In such cases you could attempt to use the assignment list1;
statement (=), as follows:

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 27
0132130807
Copying
Arrays
• In Java, you can use assignment statements to copy primitive data type
variables, butlist2
not arrays.
= does not copy the contents of the array
• This statementlist1; referenced by list1 to
• list2,
But, copies the reference value ( the address of the location in the memory)
from list1 to list2.
• After this statement, list1 and list2 reference to the same array.
• The array previously referenced by list2 is no longer referenced; it becomes
garbage, which will
be automatically collected by the Java Virtual Machine.

• There are three ways to copy arrays:


– Use the arraycopy method in the System
–– Use
Useathe
static loop to copy
clone individual
method class.
to elements one by one.
copy arrays.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 28
0132130807
Copying
Arrays
//Method1. Using a
loop int[] = {2, 3, 1, 5, 10};
sourceArray
int[] = new
targetArray int[sourceArray.length];
for (int i = 0; < sourceArrays.length; i++)
i
targetArray[i] = sourceArray[i];
//Method2. Using the arraycopy utility
//Syntax: Arraycopy (sourceArray, src_pos, targetArray, tar_pos,
length);
// see the following example:
System.arraycopy(sourceArray, 0, targetArray, 0,
sourceArray.length);

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 29
0132130807
WAP to copy array element form source array to target array.

import java.util.ArrayList;
import java.util.Collections;
class List
{
public static void main(String args[])
{
int[] sourceArray = {2, 3, 1, 5, 10};
int[] targetArray = new int[sourceArray.length];
for (int i = 0; i < sourceArray.length; i++)
targetArray[i] = sourceArray[i];
System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length);
for (int i = 0; i < targetArray.length; i++) // for-loop to display target
array//
System.out.print(targetArray[i] +" ");
}
}
WAP to copy array element form source array to
target array
import java.util.ArrayList;
import java.util.Collections;
class List
{
public static void main(String args[])
{
int[] sourceArray = {2, 3, 1, 5, 10, 7, 9, 10};
int[] targetArray = {2, 2, 2, 2, 2, 2, 2, 2} ;
System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length); //syntax for copy
array
for (int i = 0; i < targetArray.length; i++)
System.out.print(targetArray[i] +" ");
}
}

OUTPUT: 2, 3, 1, 5, 10, 7, 9, 10
Passing Arrays to
Methods
public static void printArray( int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}

//Example1. Invoke the method

int[] list = {3, 1, 2, 6, 4,

2};
printArray (list);

//Example2. Invoke
the method
printArray( new
int[]{3, 1, 2, 6, 4,
2} Programming,
Liang, Introduction to Java ); Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 32
0132130807
WAP to passing array elements to the the method in java

import java.util.ArrayList;
import java.util.Collections;

class List
{
public static void printArray( int[] array)
{
for (int i = 0; i < array.length; i++)
{
System.out.print(array[i] + " ");
}
}

public static void main(String args[])


{
int[] list = {3, 1, 2, 6, 4, 2, 8};
printArray (list); // calling method//
}
}

OUTPUT: 3, 1, 2, 6, 4, 2, 8
8. Write a Java program to create a new array list, add the following data {PHP, Java, C++, Python}
and print out the collection.
a. Insert element JavaScript into the array list at the index one.
b. Remove the third element from array list.
c. Sort the array list.
d. Use for loop or for each to display all elements from the array list
import java.util.ArrayList;
import java.util.Collections;
class List
{
public static void main(String args[])
{
ArrayList<String> list = new ArrayList<>();
list.add("PHP");
list.add("Java");
list.add("C++");
list.add("Python");
String list = {“PHP”, “Java”, “C++”, “Python”};
list.add(1,"JavaScript"); //a
list.remove(2); //b
Collections.sort(list); //c
for(String x: list) //d
{
System.out.println(x);
}
}}
OUTPUT:
C++
JavaScript
PHP
Python
Pass By
Value
• Java uses pass-by-value to pass arguments to a method.
• There are important differences between passing the values of
variables of primitive
data types and passing arrays.
– For an argument of a primitive type, the argument’s value is
passed.
– For an argument of an array type, the value of the argument is
a reference to an array; this reference value is passed to the
method.
– Semantically, it can be best described as pass-by-sharing, that
is, the array in the method is the same as the array being
passed.
• Thus, if you change the array in the method, you will see the
change outside the method.

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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 36
0132130807
WAP in java for Pass By Value in array.
class A
{
public static void main(String args[])
{
int x = 5; // variable declaration//
int[] y = new int [10]; // no value but has size 10 of array
Moosa(x,y);
System.out.println("x is :" +x);
System.out.println("y[0] is :" +y[0]);
}
public static void Moosa(int n, int[] m)
{
n =10;
m[0]= 1111111;
}
}
OUTPUT
x is :5
y[0] is :1111111
Call Stack: It is one of the types of memory to store the
initialize value.
• When invoking m(x, y), the values of x and y are passed to number and numbers.
Since y contains
the reference value to the array, numbers now contains the same reference value
to the same array.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 38
0132130807
Call
Stack
• When invoking m(x, y), the values of x and y are passed to number and numbers.
Since y contains the
reference value to the array, numbers now contains the same reference value to
the same
Stac array. Hea
k p
Space required
for method m
int[] The arrays
numbers:
int number:reference 555 are stored in
1001 5
Space required for 0 a heap.
the main method
int[] reference Array of ten int
y: int values is stored
x: 1 0 here

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 39
0132130807
Hea
p
• The Java Virtual Machine stores the array in an area of memory, called heap, which
is used for
dynamic memory allocation where blocks of memory are allocated and freed in an
arbitrary order.
Heap

The arrays are


5555
0 stored in a
Space required for the heap.
main method
int[] y: reference
int x: 0
1

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 40
0132130807
Returning an Array from a
Method
• int[] list1 = new int[]{1, 2, 3, 4, 5,
6};
• int[] list2 = reverse(list1);

public static int[] reverse(int[]


list)
{
int[] result = new
int[list.length];
for (int i = 0, j = result.length -
1; i < list.length; i++, j--)
{
result[j] = list[i];
}
return result;
} Output: {6,5,4,3,2,1}

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 41
0132130807
WAP for reverse array elements by using swapping in
java.
public
{
class ReverseArray

public static void main(String[] args)


{
int[] array = {1, 2, 3, 4, 5};
int n = array.length;
// Reverse the array
for (int i = 0; i < n / 2; i++)
{ //swapping the array elements//
int temp = array[i];
array[i] = array[n - i - 1];
array[n - i - 1] = temp;
}
System.out.print("The reverse of array is : ");
// Print the reversed array
for (int num : array)
{
System.out.print(num + " ");
}
}
}
OUTPUT: 5, 4, 3, 2, 1
WAP to enter array size, display it, reserve it, find even or odd elements in the given array

import java.util.Scanner; //Reverse the array//


public class ReverseArray System.out.print("The numbers in reverse:");
{ for (int i= n-1 ; i>=0 ;i-- )
public static void main(String[] args) System.out.print(arr[i]+" ");
{ System.out.println( " ");
Scanner input = new Scanner(System.in); // Even or ODD array elements//
System.out.print("Please enter how many numbers: "); for (int i = 0; i < n; i++)
int n = input.nextInt(); {
int arr[]= new int[n]; if (arr[i] % 2 == 0)
System.out.print("Please enter the numbers:"); {
// Reading the data// System.out.println(arr[i] + " is an Even number.");
for (int i=0; i< n; i++) }
arr[i] = input.nextInt(); else
// Printing in order// {
System.out.print("The numbers in order:"); System.out.println(arr[i] + " is an Odd number.");
for (int i=0 ; i < n; i++) }
System.out.print(arr[i]+" "); }
System.out.println( " "); }
}
Problem: Counting Occurrence of
Each Letter
• Generate 100 lowercase letters randomly and assign to an
array of characters.
• Count the occurrence of each letter in the array.
(a) Executing (b) After exiting
createArray in Line 6 createArray in Line 6

Stack Heap Stack Heap

Space required for the


Array of 100 Array of 100
createArray method
characters characters
char[] chars: ref

Space required for the Space required for the


main method main method
char[] chars: char[] chars:
ref ref

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

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

You might also like