Arrays and Detailed explanation of Array

JasmineBeulah 17 views 60 slides Aug 28, 2024
Slide 1
Slide 1 of 60
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60

About This Presentation

Easy learning -Arrays in Java


Slide Content

Arrays in Java Jasmine Beulah Gnanadurai , PhD 22-01-2024 1

Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average. 22-01-2024 2

Introducing Arrays Array is a data structure that represents a collection of the same types of data. 22-01-2024 3

Declaring Array Variables 22-01-2024 4 datatype[] arrayRefVar ; Example: double[] myList ; datatype arrayRefVar []; // This style is allowed, but not preferred Example: double myList [];

Creating Arrays 22-01-2024 5 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.

Declaring and Creating in One Step 22-01-2024 6 datatype[] arrayRefVar = new datatype[ arraySize ]; double[] myList = new double[10]; datatype arrayRefVar [] = new datatype[ arraySize ]; double myList [] = new double[10];

The Length of an Array 22-01-2024 7 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

Indexed Variables 22-01-2024 8 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, 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];

Using Indexed Variables 22-01-2024 9 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];

Array Initializers 22-01-2024 10 Declaring, creating, initializing in one step: double[] myList = {1.9, 2.9, 3.4, 3.5}; This shorthand syntax must be in one statement.

Declaring, creating, initializing Using the Shorthand Notation 22-01-2024 11 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;

CAUTION 22-01-2024 12 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};

13 Trace Program with Arrays public class Test { public static void main(String[] args ) { int [] values = new int [5]; for ( int i = 1; i < 5; i ++) { values[ i ] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line is executed, value[1] is 1 22-01-2024

14 Trace Program with Arrays public class Test { public static void main(String[] args ) { int [] values = new int [5]; for ( int i = 1; i < 5; i ++) { values[ i ] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After i++, i becomes 2 22-01-2024

15 Trace Program with Arrays public class Test { public static void main(String[] args ) { int [] values = new int [5]; for ( int i = 1; i < 5; i ++) { values[ i ] = i + values[i-1]; } values[0] = values[1] + values[4]; } } i (= 2) is less than 5 22-01-2024

16 Trace Program with Arrays public class Test { public static void main(String[] args ) { int [] values = new int [5]; for ( int i = 1; i < 5; i ++) { values[ i ] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line is executed, values[2] is 3 (2 + 1) 22-01-2024

17 Trace Program with Arrays public class Test { public static void main(String[] args ) { int [] values = new int [5]; for ( int i = 1; i < 5; i ++) { values[ i ] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this, i becomes 3. 22-01-2024

18 Trace Program with Arrays public class Test { public static void main(String[] args ) { int [] values = new int [5]; for ( int i = 1; i < 5; i ++) { values[ i ] = i + values[i-1]; } values[0] = values[1] + values[4]; } } i (=3) is still less than 5. 22-01-2024

19 Trace Program with Arrays public class Test { public static void main(String[] args ) { int [] values = new int [5]; for ( int i = 1; i < 5; i ++) { values[ i ] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line, values[3] becomes 6 (3 + 3) 22-01-2024

20 Trace Program with Arrays public class Test { public static void main(String[] args ) { int [] values = new int [5]; for ( int i = 1; i < 5; i ++) { values[ i ] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this, i becomes 4 22-01-2024

21 Trace Program with Arrays public class Test { public static void main(String[] args ) { int [] values = new int [5]; for ( int i = 1; i < 5; i ++) { values[ i ] = i + values[i-1]; } values[0] = values[1] + values[4]; } } i (=4) is still less than 5 22-01-2024

22 Trace Program with Arrays public class Test { public static void main(String[] args ) { int [] values = new int [5]; for ( int i = 1; i < 5; i ++) { values[ i ] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this, values[4] becomes 10 (4 + 6) 22-01-2024

23 Trace Program with Arrays public class Test { public static void main(String[] args ) { int [] values = new int [5]; for ( int i = 1; i < 5; i ++) { values[ i ] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After i++, i becomes 5 22-01-2024

24 Trace Program with Arrays public class Test { public static void main(String[] args ) { int [] values = new int [5]; for ( int i = 1; i < 5; i ++) { values[ i ] = i + values[i-1]; } values[0] = values[1] + values[4]; } } i ( =5) < 5 is false. Exit the loop 22-01-2024

25 Trace Program with Arrays public class Test { public static void main(String[] args ) { int [] values = new int [5]; for ( int i = 1; i < 5; i ++) { values[ i ] = i + values[i-1]; } values[0] = values[1] + values[4]; } } After this line, values[0] is 11 (1 + 10) 22-01-2024

Initializing arrays with input values 22-01-2024 26 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 22-01-2024 27 for ( int i = 0; i < myList.length; i++) { myList[i] = Math.random() * 100; }

Printing arrays 22-01-2024 28 for ( int i = 0; i < myList.length; i++) { System.out.print(myList[i] + " "); }

Summing all the elements 22-01-2024 29 double total = 0; for (int i = 0; i < myList.length ; i ++) { total += myList [ i ]; }

Finding the largest element 22-01-2024 30 double max = myList [0]; for ( int i = 1; i < myList.length ; i ++) { if ( myList [ i ] > max) max = myList [ i ]; }

Random Shuffle 22-01-2024 31

Shifting Elements 22-01-2024 32

Enhanced for Loop (for-each loop) 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. 22-01-2024 33

Self-check 22-01-2024 34 Write an enhanced for loop that prints all elements in the array values . Answer: for (double x: values) { System.out.println(x); }

Read one hundred numbers, compute their average, and find out how many numbers are above the average. int n1, n2, … , n100; Scanner input = new Scanner(System.in); n1 = input.nextInput (); n2 = input.nextInput (); n3 = input.nextInput (); ..... n100 = input.nextInput (); 22-01-2024 35

Solution through Arrays int [] n = new int[100]; Scanner input = new Scanner(System.in); for (int i =0; i < 100; i ++) { n[ i ] = input.nextInt (); } 22-01-2024 36

Copying Arrays 22-01-2024 37 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;  

Copying Arrays 22-01-2024 38 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 ];

Passing Arrays to Methods 22-01-2024 39 public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } } Invoke the method int[] list = {3, 1, 2, 6, 4, 2}; printArray(list); Invoke the method printArray (new int[]{3, 1, 2, 6, 4, 2}); Anonymous array

Searching Arrays 22-01-2024 40 Searching is the process of looking for a specific element in an array; for example, discovering whether a certain score is included in a list of scores. Searching is a common task in computer programming. There are many algorithms and data structures devoted to searching. In this section, two commonly used approaches are discussed, linear search and binary search .

41 Linear Search Animation 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 6 4 1 9 7 3 2 8 3 3 3 3 3 3 Key List 22-01-2024

Binary Search 22-01-2024 42 For binary search to work, the elements in the array must already be ordered. Without loss of generality, assume that the array is in ascending order. e.g., 2 4 7 10 11 45 50 59 60 66 69 70 79 The binary search first compares the key with the element in the middle of the array.

Binary Search, cont. 22-01-2024 43 If the key is less than the middle element, you only need to search the key in the first half of the array. If the key is equal to the middle element, the search ends with a match. If the key is greater than the middle element, you only need to search the key in the second half of the array. Consider the following three cases:

44 Binary Search 1 2 3 4 6 7 8 9 1 2 3 4 6 7 8 9 1 2 3 4 6 7 8 9 8 8 8 Key List 22-01-2024

45 Binary Search 22-01-2024

46 Binary Search 22-01-2024

47 Binary Search The binarySearch method returns the index of the element in the list that matches the search key if it is contained in the list. Otherwise, it returns -insertion point - 1. The insertion point is the point at which the key would be inserted into the list. 22-01-2024

2D Array Declaration and Creation 2D arrays are used to store a matrix or a table Declaring Array Variables elementType [][] arrayRefVar ; e.g. int [][] matrix; Declaration of an array variable does not allocate any space in memory for the array Creating Arrays arrayRefVar = new elementType [ rowSize ][ columnsize ]; e.g. int [][] matrix = new int [5][5]; 22-01-2024 48

2D Array Declaration and Creation Assigning Value to elements arrayRefVar [index2][index2] = value; e.g. matrix[2][1] = 7; 22-01-2024 49

Array Size A two-dimensional array is actually an array in which each element is a one-dimensional array If x = new int [3][4] then x[0], x[1], and x[2] are one-dimensional arrays and each contains four elements 22-01-2024 50

Initializing and Processing 2D Arrays 22-01-2024 51

Some Examples of Processing 2D Arrays 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 (); } } 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); } } Displaying arrays for (int row = 0; row < matrix.length; row++) { for (int column = 0; column < matrix[row].length; column++) { System.out.print(matrix[row][column] + " "); } 22-01-2024 52

Multi Dimensional Arrays n-dimensional Array means collection of (n-1)-dimensional Arrays The way to declare two-dimensional array variables and create two-dimensional arrays can be generalized to declare n-dimensional array variables 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]; 22-01-2024 53

ArrayList Useful class for storing objects Arrays can be used to store objects but once the array is created, its size is fixed. Java provides the ArrayList class that can be used to store an unlimited number of objects ArrayList supports dynamic arrays Defined in java.util package 22-01-2024 54

ArrayList Constructors of ArrayList class are ArrayList () : creates an empty array list with an initial capacity sufficient to hold 10 elements. e.g. ArrayList list =new ArrayList (); ArrayList ( int capacity) : creates an array list that has the specified initial capacity. e.g. ArrayList list =new ArrayList (20); ArrayList (Collection c) : creates an array list that is initialized with the elements of the collection c. e.g. ArrayList l = new ArrayList (list); Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged 22-01-2024 55

Methods of ArrayList 1. void add( int index, Object element) Inserts the specified element at the specified position index in this list. Throws IndexOutOfBoundsException if the specified index is is out of range . 2. boolean add(Object o) Appends the specified element to the end of this list. 3. boolean addAll (Collection c ) Appends all of the elements in the specified collection to the end of this list. Throws NullPointerException if the specified collection is null. 4. boolean addAll ( int index, Collection c ) Inserts all of the elements of the specified collection into this list, starting at the specified position. Throws NullPointerException if the specified collection is null. 22-01-2024 56

Methods of ArrayList 5. void clear() : Removes all of the elements from this list. 6. Object remove( int index) : Removes the element at the specified position in this list. 7. Object clone() : Returns a shallow copy of this ArrayList . 8. int size(): Returns the number of elements in the list. 9. boolean contains(Object o): Returns true if this list contains the specified element. 22-01-2024 57

Methods of ArrayList 10. Object get ( int index): Returns the element at the specified position in this list. 11. Object set( int index, o Object): Sets the element at the specified index. 12. int indexOf(Object o): Returns the index in this list of the first occurrence of the specified element, or -1 if the List does not contain the element. 13. int lastIndexOf(Object o): Returns the index in this list of the last occurrence of the specified element, or -1. 14. void ensureCapacity ( int minCapacity ) : Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. 22-01-2024 58

Arrays vs ArrayList 22-01-2024 59

22-01-2024 60
Tags