Arrays Java programming language provides a data structure









![The Assignment Operators and Arrays int[ ] list. A = { 5, 10, 15, The Assignment Operators and Arrays int[ ] list. A = { 5, 10, 15,](https://slidetodoc.com/presentation_image/5fd01ac64f0531551d34803edd2bbda7/image-10.jpg)








![Array example 5 static final int N = 26; public static void main (String[] Array example 5 static final int N = 26; public static void main (String[]](https://slidetodoc.com/presentation_image/5fd01ac64f0531551d34803edd2bbda7/image-19.jpg)




![Insertion sort implementation int [ ] arr = { 3, 9, 6, 1, 2 Insertion sort implementation int [ ] arr = { 3, 9, 6, 1, 2](https://slidetodoc.com/presentation_image/5fd01ac64f0531551d34803edd2bbda7/image-24.jpg)






![Binary search implementation int [ ] arr = { -1, 5, 6, 18, 19, Binary search implementation int [ ] arr = { -1, 5, 6, 18, 19,](https://slidetodoc.com/presentation_image/5fd01ac64f0531551d34803edd2bbda7/image-31.jpg)














![example 3 solution public static void main(String[] args) { String st = reader. next(); example 3 solution public static void main(String[] args) { String st = reader. next();](https://slidetodoc.com/presentation_image/5fd01ac64f0531551d34803edd2bbda7/image-46.jpg)







![Lengths of Two-dimensional arrays int[ ][ ] x = new int[3][4]; for (int i Lengths of Two-dimensional arrays int[ ][ ] x = new int[3][4]; for (int i](https://slidetodoc.com/presentation_image/5fd01ac64f0531551d34803edd2bbda7/image-54.jpg)


![Lengths of Two-dimensional arrays, example. public static void main(String[ ] args) { String[ ][ Lengths of Two-dimensional arrays, example. public static void main(String[ ] args) { String[ ][](https://slidetodoc.com/presentation_image/5fd01ac64f0531551d34803edd2bbda7/image-57.jpg)






- Slides: 63

Arrays ● Java programming language provides a data structure called the array ( ) מערך , which can store a fixed-size sequential collection of elements of the same type. ● Arrays are widely used within Java programming for different purposes such as sorting, searching and etc. 1

Problems with simple variables • Hard to give up values high number of variables. • Complex to sort a high number of variables by value. • Impossible to use loops. Example problem: Read one hundred numbers, compute their average, and find out how many numbers are above the average. We can use an array instead of a variables. 2

Array definition • An array ( ) מערך is a collection of variables of the same data type, and the collection is assigned a name. • Array can be declared for any type. • In Java an array is an object ( ) עצם. • Each variable within the collection is called an array element. • An array element is identified by combining the array name and a unique index ( ) אינדקס. An index is an integer from zero to 1 minus the maximum number of elements in the array. An array of size N is indexed from 0 to N – 1. • Array examples: – – list of students’ marks series of numbers entered by user vectors matrices 3

Array indexing In Java , array indexes always begin at zero. The array my. List has 10 values, indexed from 0 to 9. The i-th element of array my. List is specified by my. List[i-1]. 4

Declaring array variables ● In Java arrays are objects ( ) עצם. To create an array, the reference ( )הפניה to the array must be declared. ● The array can be created using the new operator, which allocates memory space to store values. Examples: double [ ] my. List = new double [ 10 ]; The variable my. List is declared to be an array of 10 real numbers whose type is written as double[ ]. int [ ] stud. Grades = new int [ 85 ]; The variable stud. Grades is declared to be an array of 85 integer numbers whose type is written as int[ ]. Note: once an array is declared to be a certain size, the number of values it can hold cannot be changed. 5

Default values and initialization ● When an array is created, its elements are assigned the default value of : 0 for the numeric primitive data types 'u 0000' for char data types False for boolean data types. ● Declaring, creating, initializing in one step: double [ ] my. List 1 = { 1. 9, 2. 9, 3. 4, 3. 5 }; Note: Don’t use new operator if you plan to initialize the array. 6

Accessing array elements ● To access a value in an array, we use the name of array followed by the index in square brackets. int [ ] arr = { 69, 61, 73, 19, 37 }; arr[ 2 ] = 95; // initial value was 73 ● Array indexes are integers and we can use integer expression to specify the index. int a = 7, b = 2, c = -3; arr[ a/b ] = 71; // initial value was 19 System. out. println( arr[a + c] ); // output value is 37 NOTE : when accessing array elements, be careful to ensure that the index stays within the array bounds. 7

The length of an array • In order to get the number of elements in an array, you can use the length attribute of an array. • The length attribute of an array returns the size of the array ( number of elements). • It can be used by writing array. Name. length For example : int a = my. List. length; // a = 10 int b = stud. Grade. length; // b = 85 8

Array as Java object ● Java array is a container object that holds a fixed number of values of a single type. ● The array declaration allocates only enough space for a reference to an array but doesn't create the actual array object. For example: reference int[ ] num = new int[5]; 9
![The Assignment Operators and Arrays int list A 5 10 15 The Assignment Operators and Arrays int[ ] list. A = { 5, 10, 15,](https://slidetodoc.com/presentation_image/5fd01ac64f0531551d34803edd2bbda7/image-10.jpg)
The Assignment Operators and Arrays int[ ] list. A = { 5, 10, 15, 20, 25, 30, 35 }; int[ ] list. B = new int[7]; 10

The Assignment Operators and Arrays after assignment statement List. B = List. A; 11

Array example 1 The next program section reads N integers into an array and then reverses them and prints. N value reads during the program execution. 5 15 103 -2 71 Before revers 71 -2 103 15 5 After revers 12

Example 1 - solution System. out. print( "Enter the number of array elements : “ ); int [ ] arr = new int [reader. next. Int()]; number of array elements reads during the program running for (int i = 0; i < arr. length; i++) { System. out. print("Enter number "+ (i+1) + " integer : “ ); arr[i] = reader. next. Int(); } // for (int i = 0; i < arr. length/2; i++) It is often convenient to use for loops when handling array, because { the number of its elements is constant. int temp = arr[i]; arr[i] = arr[arr. length – i - 1]; arr[arr. length-i-1] = temp; } // for System. out. println(" The numbers in revers order : "); for (int i = 0; i <arr. length; i++) System. out. println(arr[i]); 13

Array example 2 This program reads N integer number sequence and builds an array. The program builds an array from a sequence ( some numbers can appear twice or more in the sequence but appears only once in the array ). For example: N = 9 and input sequence is 9, 9, 5, 4, 4, 4, 1, 1, 7 arr 0 1 2 3 4 5 6 7 8 9 5 4 1 7 0 0 Note: maximum array’s elements is N , because each number can appears only once in the sequence. 14

Example 2 - solution static final int N = 9; public static void main (String[] args) { int [ ] arr = new int[N]; int j = 1; // array index int num; // input variable arr[0] = reader. next. Int(); for (int i = 0; i < N - 1; i++) { num = reader. next. Int(); if(num != arr[j-1]) { arr[j] = num; j++; } //if } // for(int i = 0; i < j; i++) System. out. println(arr[i]); } // main final keyword when used with a variable makes it a constant. 15

Array example 3 This program section reads 10 integers into an array, finds the max and min values of array elements and prints them. If a variable is marked as final then the value of that variable cannot be changed i. e final keyword when used with a variable makes it a constant. static final int N=10; public static void main (String[] args) { int [] arr = new int[N]; for (int i = 0; i < N; i++) arr[i] = reader. next. Int(); int max = arr[0], min = arr[0]; for (int i = 1; i < N; i++) { max = (arr[i]>max) ? arr[i] : max; min = (arr[i]<min) ? arr[i] : min; } //for System. out. println(" The max element is : "+max); System. out. println(" The min element is : "+min); } //void main if (arr[i]) > max = arr[i]; else max = max; 16

Array example 4 This program calculates the number of different values in array of integers. public static void main (String[] args) { int a[ ] = { 5, 5, 2, 9, 3, 2, 5, 9, 3, 5 }; // array of integers int i, j; // loop counters int count = 1; // accumulator for(i =1; i < a. length; i++) { for(j = 0; j < i; j++) if(a[j] == a[i]) break; if(j == i) count++; } // for System. out. println(“The number of different values is : “ + count); } // main 17

Array example 4 Trace table ( i < 3 only ) count i i<3 1 T j j<i a[ j ] == a[ i ] 0 T T 0 T F 1 T F 2 F 1 2 T public static void main (String[] args) { int a[ ] = { 5, 5, 2 }; // array of integers int i, j; // loop counters int count = 1; // accumulator for(i =1; i < a. length; i++) { j == for(j = 0; j < i; j++) i if(a[j] == a[i]) break; if(j == i) count++; F } // for System. out. println(count); } // main T 2 18
![Array example 5 static final int N 26 public static void main String Array example 5 static final int N = 26; public static void main (String[]](https://slidetodoc.com/presentation_image/5fd01ac64f0531551d34803edd2bbda7/image-19.jpg)
Array example 5 static final int N = 26; public static void main (String[] args) { int [] arr = new int[N]; int m = 0; // help variable This program reads 100 letters and …? for (int i = 0; i < N; i++) arr[i] = 0; for (int i = 0; i < 100; i++) { System. out. println(" Enter a letter: "); char ch = reader. next(). char. At(0); arr[ch – ‘a’] ++; } // for (int i = 1; i < N; i++) if(arr[i] > arr[m]) m = i; char mch = (char)(m + ’a’); System. out. println(" mch : “ + mch); 19 } // main

Sorting ( )מיון • Sorting is the process of arranging a list of items in well – defined order. • Sorting values of array elements is one of the basic array manipulations. • Many sorting algorithms have been developed over the years. In this course we examine two sorting algorithms: selection sort ( )מיון בחירה and insertion sort ( מיון )הכנסה. 20

Selection sort algorithm The selection sort algorithm selects for each position in the list the value, that should go in this position, and puts it there. 23 15 6 7 30 Scan starting with 23. 6 is smallest. Exchange 6 and 23 6 15 23 7 30 Scan starting with 15. 7 is smallest. Exchange 7 and 15 6 7 23 15 30 Scan starting with 23. 15 is smallest. Exchange 15 and 23 6 7 15 23 30 Scan starting with 23. 23 is smallest. Exchange 23 and 23 6 7 15 23 30 21

Selection sort implementation This program section uses a selection sort to arrange a list of integer values into ascending order ( עלה סדר ). The outer loop controls the position where int [ ] arr = { 23, 15, 6, 7, 20 }; for(int i = 0; i < arr. length; i++) the next smallest value will be stored. { int min_pos = i; for(int j = i+1; j < arr. length; j++) { The inner loop finds the smallest value in if ( arr[j] < arr[min_pos] ) the rest of the list. min_pos = j; When the smallest value is determined, it is int temp = arr[i]; // help variable exchanged with the value stored at the arr[i] = arr[min_pos]; index. arr[min_pos] = temp; } // inner for } // outer for The algorithm can easily be changed to put values in descending order ( יורד ) סדר by finding the largest value each time. 22

Insertion sort algorithm The insertion sort algorithm works by inserting each value into a previously sorted subset of the list. 3 9 6 1 2 3 is sorted. Shift nothing. Insert 9. 3 9 6 1 2 3 and 9 are sorted. Shift 9 to the right. Insert 6. 3 6 9 1 2 3 , 6 and 9 are sorted. Shift 9, 6 and 3 to the right. Insert 1. 1 3 6 9 2 1, 3 , 6 and 9 are sorted. Shift 9, 6 and 3 to the right. Insert 2. 1 2 3 6 9 All values are sorted 23
![Insertion sort implementation int arr 3 9 6 1 2 Insertion sort implementation int [ ] arr = { 3, 9, 6, 1, 2](https://slidetodoc.com/presentation_image/5fd01ac64f0531551d34803edd2bbda7/image-24.jpg)
Insertion sort implementation int [ ] arr = { 3, 9, 6, 1, 2 }; for (int i = 1; i < arr. length; i++) { The outer loop controls the index in the array of the next int j = i; value to be inserted. int a = arr[i]; while ( j > 0 && arr[ j-1] > a) { arr[ j ] = arr[ j-1]; j--; } // block while The inner loop compares the current insert values with values stored with lower indexes. arr[ j ] = a; If the current insert value is less then the value at j position, that value is shifted to the right. } // block for 24

Java searching ( )חיפוש • Searching ( )חיפוש is an operation which finds the location of a given element in an array. • The search is said to be successful or unsuccessful depending on whether the element that is to be searched is found or not. • Definition: A key is a value that you are looking for in an array. If found, the index of the first location of the key will be returned. If not found, a value of -1 will be returned. • In this course we examine two searching algorithms: - linear search ( סדרתי )חיפוש - binary search ( בינארי )חיפוש. 25

Linear search • The simplest type of search is the liner (sequential) search. • In the liner search, each element of the array is compared to the key, in the order it appears in the array, until the desired element is found. System. out. println( “enter search key”); int num = reader. next. Int(); // input key value boolean flag = false; This searching type can be applied for( int i = 0; i < arr. length; i++) to a sorted or an unsorted list. { if (arr [i] == num) { Searching in case of unsorted list flag = true; starts from the 0 th element and continues break; until the element is found or the end of list is } // if reached. } // for if (flag ) System. out. println(num + " is at position “ + i); else System. out. println(num + " not found "); 26

Linear search in sorted array int i; // loop counter System. out. println( “enter search key” ); int num = reader. next. Int(); // input key value for(i=0; i< arr. length && num > = arr[i]; i++) { if (arr [i] == num) { System. out. println(num + " is at position "+i); break; In case of sorted list we breaks the loop if } the key value founded. } //for if (i==0 || i==arr. length || num>arr[i] ) System. out. println(num + " not found "); 27

Binary search example 1 Index 0 1 2 3 4 5 6 7 8 9 Find 6 in {-1, 5, 6, 18, 19, 25, 46, 78, 102, 114 }. low index = 0, high index = 9. • Step 1 (middle element is 19 > 6): middle index = ( 0 + 9 ) / 2 = 4 low index = 0, high index = 4 - 1=3 • Step 2 (middle element is 5 < 6): middle index = (0 + 3 ) / 2 = 1 low index =0 +1, high index = 3 • Step 3 (middle element is 6 == 6): middle index= (1 + 3 ) / 2 = 2 searched element is found ! 28

Binary search example 2 index 0 1 2 3 4 5 6 7 8 9 Find 103 in {-1, 5, 6, 18, 19, 25, 46, 78, 102, 114}. low index = 0, high index = 9. • Step 1 (middle element is 19 <103): middle index = ( 0 + 9 ) / 2 = 4 low index =4+1, high index = 9 • Step 2 (middle element is 78 < 103): middle index = (5 + 9 ) / 2 = 7 low index =7 +1, high index = 9 • Step 3 (middle element is 102 <103): middle index= (8 + 9 ) / 2 = 8 low index =8 +1, high index = 9 • Step 4 (middle element is 114 >103): middle index= (9 + 9 ) / 2 = 9 low index =9, high index = 9 – 1 = 8 low index > high index : searched value is absent ! 29

Binary search algorithm 1. Get the middle element; 2. If the middle element equals to the searched value, the algorithm stops; 3. Otherwise, two cases are possible: – searched value is less, than the middle element. In this case, go to the step 1 for the part of the array, before middle element. – searched value is greater, than the middle element. In this case, go to the step 1 for the part of the array, after middle element. Now we should define, when iterations should stop. First case is when searched element is found. Second one is when sub-array has no elements. In this case, we can conclude, that searched value isn't present in the array. 30
![Binary search implementation int arr 1 5 6 18 19 Binary search implementation int [ ] arr = { -1, 5, 6, 18, 19,](https://slidetodoc.com/presentation_image/5fd01ac64f0531551d34803edd2bbda7/image-31.jpg)
Binary search implementation int [ ] arr = { -1, 5, 6, 18, 19, 25, 46, 78, 102, 114 }; int i = 0, h = arr. length; // low and high array indexes System. out. pirnt ("enter search key => "); int num = reader. next. Int(); // input key value while (i < h) { int mid = (i + h) / 2; // Compute mid point. if (num < arr[mid]) h = mid; else if (num > arr[mid]) i = mid+1; else { System. out. println( "found in "+mid+" position“ ); break; } //while if ( i >= h ) System. out. println(num + " not found “ ); 31

32

Strings ( )מחרוזות • Java string is a sequence of characters. • They are objects of type String. • Once a String object is created it cannot be changed. Basic string operations: String st = “Hello, word”; Note: double quotations String c 1 = “color red”, c 2, c 3 =“color green”; String bl = “ ”; // one character string String day = reader. next(); System. out. println(“ The day is : “ + day); String[ ] days ={ “Sunday”, “Monday”, “Thursday” }; 0 1 2 3 4 c o l o r 5 6 7 8 r e d Like array, every character in the string has its index, but we can’t access it directly !. index 33

String methods 1 1. string. length(); returns the length of this string. String palindrome = "Dot saw I was Tod"; This would produce int len = palindrome. length(); System. out. println( "String Length is : " + len ); String Length is : 17 2. Concatenating Strings ( + ) returns a new string that is string 1 with string 2 added to it at the end. String string 1 = "saw I was "; This would produce System. out. println( "Dot " + string 1 + "Tod“ ); Dot saw I was Tod 3. string. char. At(index); returns the character located at the String's specified index. String st = “Welcome to Java"; char result = st. char. At(11); System. out. println(result); This would produce following result : J 34

String methods 2 4. string 1. compare. To(sryring 2) - Compares two strings lexicographically: - The result is zero if the strings are equal. - The result is a negative integer if string 1 lexicographically precedes the string 2 string. - The result is a positive integer if string 1 lexicographically follows the string 2 string. We cannot just compare strings contents by simple if statement : String st 1 = “Hello”; String st 2 = “Hello”; if(st 1==st 2) { … } st 1 H e l l o st 2 H e l l o because st 1 and st 2 are memory addresses of st 1 and st 2. 35

compare. To method - cont. • Characters in Java are based on Unicode character set, which defines an ordering of all possible characters that can be used. • The compare. To method can be used to determine the relative ( lexicographic ) order of strings. For example: String st 1 = “AARBNML”, st 2 = “AARZK”; st 1 st 2 0 1 2 3 4 5 6 A A R B N M L 0 1 2 3 4 A A R Z K • int x=st 1. compare. To(st 2); // x = - 24: 0066 - 0090 36

compare. To method - examples For example: String str 1 = "Strings are immutable"; String str 2 = "Strings are immutable"; String str 3 = "Integers are not immutable"; int result = str 1. compare. To( str 2 ); System. out. println(result); result = str 2. compare. To( str 3 ); System. out. println(result); result = str 3. compare. To( str 1 ); System. out. println(result); This produces following result: 0 10 -10 37

String methods 3 5. string. substring ( index ) returns a new string that is a substring of the string. The substring begins with the character at the specified index and extends to the end of this string. String st 1 = “abcdefg”; String st 2 = st 1. substring(3); // st 2 = “defg” String st 3 = st 1. substring(6); // st 3 = “g” 6. string 1. index. Of(string 2) returns the index within string 1 of the first occurrence of the substring 2. If it does not occur as a substring, -1 is returned. String st 1 = “abcdefg”, st 2 = “cd”, st 3 = “abc”; int p 1 = st 1. index. Of(st 2); // p 1= 2 int p 2 = st 1. index. Of(st 3); // p 2 = 0 int p 3 = st 1. index. Of(“xy”); // p 3 = -1 38

String methods 4 7. string 1. index. Of(string 2, ind) returns the index within string 1 of the first occurrence of the substring 2 from the ind place. If it does not occur as a substring from ind place, -1 is returned. String st 1 = “abcdefg”; int p 1 = st 1. index. Of(“cd”, 5); // p 1= -1 int p 2 = st 1. index. Of (“cd”, 1); // p 2 = 2 int p 3 = st 1. index. Of(“ab”, 3); // p 3 = -1 8. string. substring ( start. Index, end. Index ) returns a new string that is a substring of the string. The substring begins with the character at the specified start. Index and extends to the end. Index (but not including). String st 1 = “abcdefg”; String st 2 = st 1. substring(3, 6); // st 2 = “def” String st 3 = st 1. substring(2, 5); // st 3 = “cde” 39

String methods 5 9. string 1. last. Index. Of(string 2) returns the index within string 1 of the last occurrence of the substring 2. If it does not occur as as substring, -1 is returned. String st 1 = “abcdeabfg”; int p 1 = st 1. last. Index. Of(“ab”); // p 1= 5 int p 2 = st 1. last. Index. Of (“abc”); // p 2 = 0 int p 3 = st 1. last. Index. Of(“xyz”); // p 3 = -1 10. string. replace(old. Char, new. Char) returns new string resulting from replacing all occurrences of old. Char in this string with new. Char. String s 1 = “abaabcas”; String s 2 = s 1. replace(‘a’, ‘*’); // s 2 = “*b**bc*s” 40

Empty string String in Java is considered empty if its length is zero. Empty String is represented by String literal “”. For example: String str 1 = “”; // empty string String with white space are not considered as empty String in Java. String str 2 = “ “; // five characters string We often needs to check if String is empty or not. There are two ways to find if String is empty or not. 1. Checking if String is empty by using length() Java method : if(str 1. length() == 0) …. 2. Checking if String is empty by using boolean type is. Empty() Java method : if( str 1. is. Empty() ) … 41

Empty string - example public class Empty. String. Demo { public static void main(String[ ] args) { String str = "tutorialspoint"; /* prints length of string str */ System. out. println("length of string = " + str. length()); /* checks if the string str is empty or not */ System. out. println("is this string empty? = " + str. is. Empty()); } // main } // Empty. String. Demo This will produce the following result : length of string = 14 is this string empty? = false 42

String methods - example 1 This program section reads the sentences , calculates and prints it word’s numbers. int words = 0; // words counter int i = 0; // loop counter String snc = "Welcome to Java course. "; do { This would produce 4 if( snc. char. At(i) == ' ') words++; ? i++; } while( i< snc. length( ) ); System. out. println( "The number of words is: "+ (++words)); 43

String methods - example 2 This program section reads the string and tests it. If the string is palindrome, the program prints “YES”, otherwise “NO”. public static void main(String[] args) { boolean flag = true; // help variable String str; // input string System. out. println(“Enter the string”); str = reader. next(); 0 int size = str. length(); a for(int i = 0; i <size/2 && flag; i++) if(str. char. At(i) != str. char. At( size – 1 – i) flag = false; if(flag) System. out. println(“YES”); else System. out. println(“NO”); } Size = 5 1 2 3 4 b c b a 44

String methods - example 3 This program reads the string and builds the array of all characters from the input string which appears only one time. For example: b - 2 times f - 4 times input string = "abcbdefdfffgh" output array is : d - 2 times a c e g h 45
![example 3 solution public static void mainString args String st reader next example 3 solution public static void main(String[] args) { String st = reader. next();](https://slidetodoc.com/presentation_image/5fd01ac64f0531551d34803edd2bbda7/image-46.jpg)
example 3 solution public static void main(String[] args) { String st = reader. next(); int i, j, k; // loop counters boolean flag; // help variable int len = str. length(); char[] help. Array = new char[len]; // help array for(i = 0; i < len; i++) help. Array[i] = str. char. At(i); for(i = 0; i < len-1; i++) { for(j = i+1 , flag = false; j < len; j++) if(help. Array[i] == help. Array[j]) { for(k = j ; k < len-1; k++) help. Array[k] = help. Array[k+1]; flag = true; j--; len--; } // if 46

example 3 solution, cont. if( flag ) { for(k = i ; k <len-1; k++) help. Array[k] = help. Array[k+1]; i--; len--; } // if(flag) } // outer for char[ ] fin. Arr = new char[len]; // creating output array for(i = 0; i< len; i++) fin. Arr[i] = help. Array[i]; /* printing output array */ for(i = 0; i< len; i++) System. out. print (help. Array[i]); System. out. println(); } // main 47


Exam question - solution String s = reader. next(); String fix. Str = ""; for(int i = 0; i < s. length(); i++) { if (s. char. At(i) == '. ' || s. char. At(i) == ', ') { /* Remove spaces before point or comma */ for (int j = i-1; j >= 0 && s. char. At(j) == ' '; j--) fix. Str = fix. Str. substring(0, fix. Str. length() - 1); fix. Str += s. char. At(i) + " "; /* Remove redundant spaces after point or comma */ while ( i+1 < s. length() && s. char. At(i+1) == ' ') i++; } // if else fix. Str += s. char. At(i); } // for /* Remove redundant characters after the last point */ for (int i = fix. Str. length() - 1; i >= 0 && fix. Str. char. At(i) == ' '; i--) fix. Str = fix. Str. substring(0, fix. Str. length() - 1); System. out. println( “ The new string is : ” + fix. Str); 49

Two - dimensional arrays • Java, as with most languages, supports multi-dimensional arrays - 1 dimensional, 2 -dimensional, 3 -dimensional, . . . In practice most arrays are one-dimensional, and two-dimensional. • 2 -dimensional arrays ( 2 D array) are usually represented with a row-column "spreadsheet" style. • Two-dimensional arrays are usually visualized as a matrix, with rows and columns. • Assume we have an array, arr, with two rows and four columns. int [][] arr = new int[2][4]; // Two rows and four columns Row index 0 1 2 3 0 34 15 105 -43 1 345 -73 88 66 Column index 50

Two - dimensional arrays A 2 D Array in JAVA is really an Array of Arrays: Assume we have an array : int [ ][ ] nums = new int[5][4]; The above is really equivalent to a 3 step process: 1. create the single reference nums (yellow square) int [ ][ ] nums; 2. create the array of references (blue squares) nums = new int[5][ ]; 3. this create the second level of arrays (red squares) for (int i = 0; i < 5 ; i++) nums[ i ] = new int[4]; // create arrays of integers 51

Two - dimensional arrays ● A 2 - dimensional array in Java can have different numbers of elements in different rows. In other words: a 2 -dimensional array in Java is made up with many rows of 1 - dimensional arrays. For example: NOTE : We will only discuss and use rectangular 2 -dimensional arrays in this course. 52

Declaring, Creating and Initializing You can also use an array initializer to declare, create and initialize a two-dimensional array. For example : int [ ][ ] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12} }; Same as int [ ][ ] array = new int[4][3]; array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; array[2][0] = 7; array[2][1] = 8; array[2][2] = 9; array[3][0] = 10; array[3][1] = 11; array[3][2] = 12; static final int ROW = 4; static final int COL = 3; int array = new int [ ROW ][ COL ]; for (int i = 0; i < ROW; i++) for (int j = 0; j < COL; j++) arr[i][ j ] = reader. next. Int(); Two-dimensional arrays are almost always processed with nested for loops. The two index variables are often called i and j. 53
![Lengths of Twodimensional arrays int x new int34 for int i Lengths of Two-dimensional arrays int[ ][ ] x = new int[3][4]; for (int i](https://slidetodoc.com/presentation_image/5fd01ac64f0531551d34803edd2bbda7/image-54.jpg)
Lengths of Two-dimensional arrays int[ ][ ] x = new int[3][4]; for (int i = 0; i < x. length; i++) { for (int j = 0; j < x[ i ]. length; j++) System. out. print ( “ “+x[ i ][ j ]); System. out. println ( “ “); } // for You can get the size of each dimension with the length attribute. This is the most general style. 54

Lengths of Two-dimensional arrays ● If a is a 2 - dimensional array then: a[i] is a 1 - dimensional array. In other words: a 2 - dimensional array in Java is made up with many rows of 1 -dimensional arrays. ● The variable a[i]. length contains the number of columns in row i. 55

Lengths of Two-dimensional arrays, example. This program section calculates and prints the sum of each column of a 2 D rectangular matrix. int sum; // sum of column elements for (int col = 0; col < matrix[0]. length; col++) { sum = 0; for (int row = 0; row < matrix. length; row++) sum = sum + matrix[row][col]; System. out. println("Sum of column " + (col + 1) + " = " + sum); } // outer for 56
![Lengths of Twodimensional arrays example public static void mainString args String Lengths of Two-dimensional arrays, example. public static void main(String[ ] args) { String[ ][](https://slidetodoc.com/presentation_image/5fd01ac64f0531551d34803edd2bbda7/image-57.jpg)
Lengths of Two-dimensional arrays, example. public static void main(String[ ] args) { String[ ][ ] strarray = { {"this" , "is", "the", "first", "row"}, {"this", "the", "second", "row"}, {"this", "the", "third", "row"} }; This would produce : for(int i = 0; i < strarray. length; i++) { for(int j = 0; j < strarray[ i ]. length; j++) System. out. print(strarray[ i ][ j ]+" "); System. out. println(); this is the first row } // outer for this is the second row } // main this is the third row 57

Lengths of Two-dimensional arrays, example. This program section calculates and prints the maximum element of each row in a 2 D matrix. for ( int row = 0; row < matrix. length; row++) { largest = matrix[row][0]; for (int col = 1; col < matrix[row]. length col++) if (largest < matrix[row][col]) largest = matrix[row][col]; System. out. println("The largest element of row " + (row + 1) + " = " + largest); } // outer for 58

Two - dimensional array example 1 This program section checks if the diagonal’s elements of square matrix are equal. mat. length = 4 Minor diagonal 3 0 9 -1 7 7 10 6 6 4 8 5 i mat[i][i] 0 3 1 7 2 6 3 4 int [][] mat = {{3, 0, 9, 3}, {-1, 7, 7, 2}, {10, 6, 6, -15}, {4, 8, 5, 4}}; 2 boolean flag = true; // help variable -15 int i = 0; // loop counter while ( i < mat. length && flag) 4 Main { diagonal if ( mat[ i ] != mat[ i ][mat. length - i - 1] ) flag = false; mat[i][4 -i-1] i++; } // while 3 if ( flag ) System. out. println(“Yes"); 7 else 6 System. out. println(“No"); 4 3 59

Two - dimensional array example 2 This program section transposes the integer square matrix. public static void main(String[ ] args) { System. out. print ("Enter array size: "); int size = reader. next. Int(); // size=3 int[ ][ ] a = new int[size]; for (int r = 0; r < a. length; r++) for (int c = 0; c < a[0]. length; c++) a[r][c] = reader. next. Int(); int startc = 1; for (int r = 0; r < a. length; r++) { for (int c = startc; c < a[0]. length; c++) { int temp = a[r][c]; a[r][c] = a[c][r]; a[c][r] = temp; } // inner loop startc++; } // outer loop } // main Original array: 6 7 8 4 3 1 2 9 5 Transposed array: 6 4 2 7 3 9 8 1 5 60

Matrix multiplication Typical applications in science and engineering involve implementing various mathematical operations with matrix , for example matrix multiplication: Note: the number of columns in the A matrix m equals the number of rows in the matrix B. Square matrix 61

Matrix multiplication , cont. static final int N = 3; // square matrix double[ ][ ] c = new double[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { for (int k = 0; k < N; k++) c[i][j] + = a[i][k] * b[k][j]; } // for j } // for i 62

Puzzle 63