1
Arrays
2
● Java programming language provides a data structurecalled the array ( מערך ), which can store a fixed-sizesequential collection of elements of the same type.
● Arrays are widely used within Java programmingfor different purposes such as sorting, searchingand etc.
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.
3
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
4
Array indexingIn Java ,array indexes always begin at zero.
The array myList has 10 values, indexed from 0 to 9.
The i-th element of array myList is specified by myList[i-1].
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
double[] myList = new double[10];
myList reference myList[0] myList[1]
myList[2]
myList[3]
myList[4]
myList[5]
myList[6]
myList[7]
myList[8]
myList[9]
Element value
Array reference variable
Array element at index 5
5
Element value
Array element at index 5
double[] myList = new double[10];
myList[6]
myList[7]
myList[8]
myList[9]
myList[4]
myList[5]
myList[2]
myList[3]
myList[1]
myList[0]
5.6
4.5
3.3
13.2
4
34.33
34
45.45
99.993
11123
reference
myList
Array reference variable
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 [ ] myList = new double [ 10 ];The variable myList is declared to be an array of 10 real numbers whose type is written as double [ ].
int [ ] studGrades = new int [ 85 ];The variable studGrades 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 itcan hold cannot be changed.
6
Default values and initialization● When an array is created, its elements are
assigned the default value of :0 for the numeric primitive data types'\u0000' for char data typesFalse for boolean data types.
● Declaring, creating, initializing in one step:double [ ] myList1 = { 1.9, 2.9, 3.4, 3.5 };
Note: Don’t use new operator if you plan to initialize thearray.
7
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 19System.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.
8
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 arrayName.lengthFor example :int a = myList.length; // a = 10int b = studGrade.length; // b = 85
9
Array as Java object
10
● Java array is a container object that holds a fixed number of values of asingle type.
● The array declaration allocates only enough space for a reference to anarray but doesn't create the actual array object.For example:
int [ ] num = new int[5];
reference
The Assignment Operators and Arrays
11
int [ ] listA = { 5, 10, 15, 20, 25, 30, 35 };int [ ] listB = new int[7];
The Assignment Operators and Arrays
12
Arrays after assignment statement ListB = ListA;
Array example 1
The next program section reads N integers intoan 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
13
Example 1 - solutionSystem.out.print( "Enter the number of array elements : “ );int [ ] arr = new int [reader.nextInt()];for (int i = 0; i < arr.length; i++){
System.out.print("Enter number "+ (i+1) + " integer : “ );arr[i] = reader.nextInt();
} // forfor (int i = 0; i < arr.length/2; i++) {
int temp = arr[i];arr[i] = arr[arr.length – i - 1];arr[arr.length-i-1] = temp;
} // forSystem.out.println(" The numbers in revers order : ");for (int i = 0; i
Array example 2
15
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
876543210
000071459arr
Note: maximum array’s elements is N , because each number can appearsonly once in the sequence.
Example 2 - solution
16
static final int N = 9;public static void main (String[] args) {
int [ ] arr = new int[N];int j = 1; // array indexint num; // input variablearr[0] = reader.nextInt();for (int i = 0; i < N - 1; i++){
num = reader.nextInt();if(num != arr[j-1]){
arr[j] = num;j++;
} //if} // forfor(int i = 0; i < j; i++)
System.out.println(arr[i]);} // main
final keyword when used with a variable makes it a constant.
Array example 3This program section reads 10 integers into an array, finds the max and
min values of array elements and prints them.
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.nextInt();int max = arr[0],min = arr[0];for (int i = 1; i < N; i++) {
max = (arr[i]>max) ? arr[i] : max;min = (arr[i] maxmax = arr[i];
elsemax = max;
17
Array example 4
18
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 integersint i, j; // loop countersint 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++;} // forSystem.out.println(“The number of different values is : “ + count);
} // main
Array example 4
19
public static void main (String[] args) {
int a[ ] = { 5, 5, 2 }; // array of integersint i, j; // loop countersint 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++;} // forSystem.out.println(count);
} // main
j == ia[ j ] == a[ i ]j < iji < 3icount
1
T1
FTT0
T2
FT0
FT1
F2
T
2
Trace table ( i < 3 only )
Array example 5
20
This program reads 100 letters and …?
static final int N = 26;public static void main (String[] args){
int [ ] arr = new int[N];int m = 0; // help variablefor (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().charAt(0);arr[ch – ‘a’] ++;
} // forfor (int i = 1; i < N; i++)
if(arr[i] > arr[m])m = i;
char mch = (char)(m + ’a’);System.out.println(" mch : “ + mch);
} // 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 ( מיון.(הכנסה
21
Selection sort algorithmThe 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
6 15 23 7 30
6 7 23 15 30
6 7 15 23 30
6 7 15 23 30
Scan starting with 23.6 is smallest. Exchange 6 and 23
Scan starting with 15.7 is smallest. Exchange 7 and 15
Scan starting with 23.15 is smallest. Exchange 15 and 23
Scan starting with 23.23 is smallest. Exchange 23 and 23
22
Selection sort implementation
int [ ] arr = { 23,15,6,7,20 };for(int i = 0; i < arr.length; i++){
int min_pos = i;for(int j = i+1; j < arr.length; j++){
if ( arr[j] < arr[min_pos] ){
int temp = arr[min_pos]; // help variablearr[min_pos] = arr[j];arr[j] = temp;
} // if} // inner for
} // outer for
This program section uses a selection sort to arrange a list of integer values into ascending order ( סדר עלה ).
The outer loop controls the position where the next smallest value will be stored.
The inner loop finds the smallest value in the rest of the list .When the smallest value is determined, it is exchanged with the value stored at the index.
The algorithm can easily be changed to put values in descending order ( סדר יורד )by finding the largest value each time. 23
Insertion sort algorithmThe insertion sort algorithm works by inserting each value into a previously
sorted subset of the list.
3 9 6 1 2
3 9 6 1 2
3 6 9 1 2
1 3 6 9 2
1 2 3 6 9
3 is sorted.Shift nothing. Insert 9.
3 and 9 are sorted.Shift 9 to the right. Insert 6.
3 ,6 and 9 are sorted.Shift 9,6 and 3 to the right. Insert 1.
1,3 ,6 and 9 are sorted.Shift 9,6 and 3 to the right. Insert 2.
All values are sorted24
Insertion sort implementationint [ ] arr = { 3,9,6,1,2 };for (int i = 1; i < arr.length; i++){
int j = i;int a = arr[i]; while ( j > 0 && arr[ j-1] > a){
arr[ j ] = arr[ j-1];j--;
} // block whilearr[ j ] = a;
} // block for
The inner loop compares the current insert values with values stored with lower indexes.If the current insert value is less then the value at j position, that value is shifted to the right.
The outer loop controls the index in the array of the next value to be inserted.
25
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 (בינארי .(חיפוש
26
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.nextInt(); // input key valueboolean flag = false; for( int i = 0; i < arr.length; i++){
if (arr [i] == num){
flag = true; break;
} // if } // for if (flag )
System.out.println(num + " is at position “ + i); else
System.out.println(num + " not found ");
This searching type can be applied to a sorted or an unsorted list.
Searching in case of unsorted list starts from the 0th element and continues until the element is found or the end of list is reached.
27
Linear search in sorted arrayint i; // loop counterSystem.out.println( “enter search key” );int num = reader.nextInt(); // input key valuefor(i=0; i< arr.length && num > = arr[i]; i++){
if (arr [i] == num){
System.out.println(num + " is at position "+i); break;
} } //for if (i==0 || i==arr.length || arr[i] > num)
System.out.println(num + " not found ");
In case of sorted list we breaks the loop ifthe key value founded.
28
Binary search example 1
Index
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 = 4low index = 0, high index = 4 - 1=3
• Step 2 (middle element is 5 < 6): middle index = (0 + 3 ) / 2 = 1low index =0 +1, high index = 3
• Step 3 (middle element is 6 == 6): middle index= (1 + 3 ) / 2 = 2
searched element is found !
0 1 2 3 4 5 6 7 8 9
29
Binary search example 2
index
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 high index : searched value is absent !
0 1 2 3 4 5 6 7 8 9
30
Binary search algorithm1. 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.
31
Binary search implementationint [ ] arr = { -1,5,6,18,19,25,46,78,102,114 };int i = 0,h = arr.length; // low and high array indexesSystem.out.pirnt ("enter search key => ");int num = reader.nextInt(); // input key valuewhile (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 “ );32
33
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”;String c1 = “color red”, c2, c3 =“color green”; String bl = “ ”; // one character stringString day = reader.next(); System.out.println(“ The day is : “ + day);String[ ] days ={ “Sunday”, “Monday”, “Thursday” };
Like array, every character in the string has its index,but we can’t access it directly !.
0 1 2 3 4 5 6 7 8
c o l o r r e d
index
34
Note: double quotations
String methods 11.string.length(); returns the length of this string.
String palindrome = "Dot saw I was Tod";int len = palindrome.length();System.out.println( "String Length is : " + len );
2.Concatenating Strings ( + ) returns a new string thatis string1 with string2 added to it at the end.
String string1 = "saw I was ";System.out.println( "Dot " + string1 + "Tod“ );
3.string.charAt(index); returns the character located at the String's specified index.
String st = “Welcome to Java";char result = st.charAt(11);System.out.println(result);
This would produceString Length is : 17
This would produceDot saw I was Tod
This would producefollowing result : J
35
String methods 24. string1.compareTo(sryring2) - Compares two strings lexicographically:
- The result is zero if the strings are equal. - The result is a negative integer if string1
lexicographically precedes the string2 string. - The result is a positive integer if string1 lexicographically
follows the string2 string.
We cannot just compare strings contents by simple if statement :
String st1 = “Hello”;String st2 = “Hello”;if(st1==st2) {
…}
because st1 and st2 are memory addresses of st1 and st2.
H e l l o
H e l l o
st1
st2
36
compareTo method - cont.• Characters in Java are based on Unicode character set,
which defines an ordering of all possible characters that can be used.
• The compareTo method can be used to determine the relative( lexicographic ) order of strings.
For example:String st1 = “AARBNML”, st2 = “AARZK”;
• int x=st1.compareTo(st2); // x = - 24: 0066 - 009037
0 1 2 3 4 5 6
A A R B N M L
0 1 2 3 4
A A R Z K
st1
st2
compareTo method - examples
For example:String str1 = "Strings are immutable";String str2 = "Strings are immutable";String str3 = "Integers are not immutable";
int result = str1.compareTo( str2 );System.out.println(result);result = str2.compareTo( str3 );System.out.println(result);result = str3.compareTo( str1 ); System.out.println(result);
This produces following result:
010 -10
38
String methods 35. 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 st1 = “abcdefg”;String st2 = st1.substring(3); // st2 = “defg”String st3 = st1.substring(6); // st3 = “g”
6. string1.indexOf(string2) returns the index within string1 of the first occurrence of the substring2. If it does not occur as a substring, -1 is returned.String st1 = “abcdefg”, st2 = “cd”,st3 = “abc”;int p1 = st1.indexOf(st2); // p1= 2int p2 = st1.indexOf(st3); // p2 = 0int p3 = st1.indexOf(“xy”); // p3 = -1
39
String methods 47. string1.indexOf(string2, ind) returns the index within string1 of the first
occurrence of the substring2 from the ind place . If it does not occur as a substring from ind place, -1 is returned.String st1 = “abcdefg”;int p1 = st1.indexOf(“cd”,5); // p1= -1int p2 = st1.indexOf (“cd”,1); // p2 = 2int p3 = st1.indexOf(“ab”,3); // p3 = -1
8. string.substring ( startIndex,endIndex ) returns a new string that is a substring of the string. The substring begins with the character at the specified startIndex and extends to the endIndex (but not including). String st1 = “abcdefg”;String st2 = st1.substring(3,6); // st2 = “def”String st3 = st1.substring(2,5); // st3 = “cde”
40
String methods 59. string1.lastIndexOf(string2) returns the index within string1 of the last
occurrence of the substring2. If it does not occur as as substring, -1 is returned.
String st1 = “abcdeabfg”;int p1 = st1.lastIndexOf(“ab”); // p1= 5int p2 = st1.lastIndexOf (“abc”); // p2 = 0int p3 = st1.lastIndexOf(“xyz”); // p3 = -1
10. string.replace(oldChar, newChar) returns new string resulting from replacing all occurrences of oldChar in this string with newChar.
String s1 = “abaabcas”;String s2 = s1.replace(‘a’, ‘*’); // s2 = “*b**bc*s”
41
Empty stringString in Java is considered empty if its length is zero.Empty String is represented by String literal “”.
For example:String str1 = “”; // empty stringString with white space are not considered as empty String in Java.String str2 = “ “; // 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(str1.length() == 0) ….2. Checking if String is empty by using boolean type isEmpty() Java
method :if( str1.isEmpty() ) …
42
Empty string - examplepublic class EmptyStringDemo{
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.isEmpty()); } // main
} // EmptyStringDemo
43
This will produce the following result :
length of string = 14 is this string empty? = false
String methods - example 1
int words = 0; // words counterint i = 0; // loop counterString snc = "Welcome to Java course.";do{
if( snc.charAt(i) == ' ')words++;
i++; } while( i< snc.length( ) );System.out.println( "The number of words is: "+ (++words));
This program section reads the sentences ,calculates and printsit word’s numbers.
?
This would produce 4
44
String methods - example 2
45
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 variableString str; // input stringSystem.out.println(“Enter the string”); str = reader.next();int size = str.length();for(int i = 0; i
String methods - example 3
46
This program reads the string and builds the array of all characters from the input string which appears only one time.
For example:
input string = "abcbdefdfffgh"
output array is : hgeca
b - 2 times
d - 2 times
f - 4 times
example 3 solution
47
public static void main(String[] args) {String st = reader.next();int i, j, k; // loop countersboolean flag; // help variableint len = str.length();char[] helpArray = new char[len]; // help arrayfor(i = 0;i < len;i++)
helpArray[i] = str.charAt(i);for(i = 0; i < len-1; i++){
for(j = i+1 ,flag = false; j < len; j++)if(helpArray[i] == helpArray[j]) {
for(k = j ;k < len-1; k++)helpArray[k] = helpArray[k+1];
flag = true;j--;len--;
} // if
example 3 solution, cont.
48
if( flag ) {
for(k = i ;k
Exam question example
49
כתוב תכנית הקולטת מחרוזת של טקסט ומדפיסה מחרוזת חדשה המכילה את אותו טקסט :כאשר
Exam question - solutionString s = reader.next();String fixStr = "";for(int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '.' || s.charAt(i) == ',') {/* Remove spaces before point or comma */for (int j = i-1; j >= 0 && s.charAt(j) == ' '; j--)
fixStr = fixStr.substring(0,fixStr.length() - 1);fixStr += s.charAt(i) + " ";/* Remove redundant spaces after point or comma */while ( i+1 < s.length() && s.charAt(i+1) == ' ')
i++;} // ifelse
fixStr += s.charAt(i);} // for/* Remove redundant characters after the last point */for (int i = fixStr.length() - 1; i >= 0 && fixStr.charAt(i) == ' '; i--)
fixStr = fixStr.substring(0,fixStr.length() - 1); System.out.println( “ The new string is :” + fixStr);
50
51
Multi - dimensional arrays
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 ( 2D 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
0 1 2 3
0 34 15 105 -43
1 345 -73 88 66
Column index
Row index
52
Two - dimensional arrays
53
A 2D Array in JAVA is really an Array of Arrays:
Assume we have an array :int [ ][ ] nums = new int [5][4];
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
The above is really equivalentto a 3-step process :
Two - dimensional arrays
54
● 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 rowsof 1- dimensional arrays.
For example:
NOTE : We will only discuss and use rectangular 2-dimensional arraysin this course.
Declaring, Creating and InitializingYou can also use an array initializer to declare, create and
initialize a two-dimensional array. For example :
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;
int [ ][ ] array = {{1, 2, 3},{4, 5, 6},{7, 8, 9},{10, 11, 12}
};Same as
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.nextInt();
Two-dimensional arrays are almost always processed with nested for loops. The two index variables are
often called i and j.
55
Lengths of Two-dimensional arrays
x
x[0]
x[1]
x[2]
x[0][0] x[0][1] x[0][2] x[0][3] x[1][0] x[1][1] x[1][2] x[1][3] x[2][0] x[2][1] x[2][2] x[2][3]
x.length is 3
x[0].length is 4
x[1].length is 4
x[2].length is 4
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.
56
x[2][0] x[2][1] x[2][2] x[2][3]
x[1][0] x[1][1] x[1][2] x[1][3]
x[0][0] x[0][1] x[0][2] x[0][3]
x[2].length is 4
x[1].length is 4
x[0].length is 4
x.length is 3
x[2]
x[1]
x[0]
x
Lengths of Two-dimensional arrays
57
● 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 rowsof 1-dimensional arrays.
● The variable a[ i ].length contains the number of columns in row i.
Lengths of Two-dimensional arrays, example.
58
This program section calculates and prints the sum of each column of a 2D rectangular matrix.
int sum; // sum of column elementsfor (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
Lengths of Two-dimensional arrays, example.public static void main(String[ ] args) {
String [ ][ ] strarray = {{"this" ,"is","the","first","row"},{"this","is","the","second","row"},{"this","is","the","third","row"}
};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();} // outer for
} // main59
this is the first row this is the second row this is the third row
This would produce :
Lengths of Two-dimensional arrays, example.
60
This program section calculates and prints the maximum element of each row in a 2D 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
61
Matrix addition and subtraction
● Two matrices may be added or subtracted only if they havethe same dimension;
For example, consider matrix A and matrix B:
Both matrices have the same number of rows and columns (2 rows and 3 columns), so they can be added and subtracted. Thus,
int [ ][ ] a ={ {1,4,-2,3}, {-1,2,5,3}, {9,10,-94,12} };int [ ][ ] b ={ {2,-4,5, 3}, {7,9,-7,6}, {12,-5,3,6} };int [ ][ ] c= new int [a.length][a[0].length];
for (int i = 0 ;i
Two - dimensional array example 1
3 0 9 3
-1 7 7 2
10 6 6 -15
4 8 5 4
This program section checks if the diagonal’s elements of square matrix are equal.
Minor diagonal
Main diagonal
int [ ][ ] mat = {{3,0,9,3},{-1,7,7,2},{10,6,6,-15},{4,8,5,4}};
boolean flag = true; // help variableint i = 0; // loop counterwhile ( i < mat.length && flag){
if ( mat[ i ][ i ] != mat[ i ][mat.length - i - 1] )flag = false;
i++;} // whileif ( flag )
System.out.println(“Yes");else
System.out.println(“No");
i mat[i][i] mat[i][4-i-1]
0 3 3
1 7 7
2 6 6
3 4 4
mat.length = 4
63
64
Two - dimensional array example 2This program section tests if sum of elements above the main diagonal is equal to sum ofelements below of main diagonal in N X N square matrix.
0007
0071
0711
7111
Main diagonal
0,30,20,17
1,31,271,0
2,372,12,0
73,23,13,0
N = 4
Main diagonal
1
65
Two - dimensional array example 2int arr[ ][ ]= { { 7,0,0,0 },
{ 1,7,0,0 },{ 1,1,7,0 },{ 1,1,1,7 } }; // N = 4
int s1 = 0, s2 = 0; // sums of array’s valuesfor ( int i = 0; i < N-1; i++)
for ( int j = i + 1; j < N; j++) s1+= arr[i][j]; // above
for ( int i = 1; i < N; i++) for ( int j = 0; j < i; j++)
s2+= arr[i][j]; // belowif(s1==s2)
System.out.println(" YES“);else
Sysyem.out.println(" NO“);
Two - dimensional array example 3
66
This program section transposes the integer square matrix.public static void main(String[ ] args) {
System.out.print ("Enter array size: ");int size = reader.nextInt(); // size=3int[ ][ ] a = new int[size][size];for (int r = 0; r < a.length; r++)
for (int c = 0; c < a[0].length; c++) a[r][c] = reader.nextInt();
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 loopstartc++;
} // outer loop} // main
Original array:
6 7 84 3 12 9 5
Transposed array:
6 4 27 3 98 1 5
67
Two - dimensional array example 4public static void main(String[] args){
final int ROW = 11;final int COLUMN = 11;int [ ][ ] mat = new int [ROW][COLUMN];for (int i=1; i < ROW; i++)
for (int j=1; j < COLUMN; j++)mat[ i ][ j ] = i * j;
for (int i=1; i < ROW; i++){
for (int j=1; j < COLUMN; j++) System.out.print(mat[ i ][ j ] + "\t");
System.out.println();} // outer for
} // main
68
Two - dimensional array example 4
Matrix multiplication
69
Typical applications in science and engineering involve implementing various mathematical operations with matrix ,for example matrix multiplication:
C ji,Note: the number of columns in the A matrix m equals the number of rows in the matrix B.
Square matrix
Matrix multiplication , cont.
70
static final int N = 3; // square matrixdouble[ ][ ] 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
Puzzle
71
Slide Number 1�Arrays�Problems with simple variablesArray definitionArray indexingDeclaring array variablesDefault values and initializationAccessing array elementsThe length of an arrayArray as Java objectThe Assignment Operators and ArraysThe Assignment Operators and ArraysArray example 1Example 1 - solutionArray example 2Example 2 - solutionArray example 3Array example 4Array example 4Array example 5Sorting (מיון )Selection sort algorithmSelection sort implementationInsertion sort algorithmInsertion sort implementationJava searching ( (חיפושLinear searchLinear search in sorted arrayBinary search example 1Binary search example 2Binary search algorithmBinary search implementationSlide Number 33Strings) (מחרוזותString methods 1String methods 2compareTo method - cont.compareTo method - examplesString methods 3String methods 4String methods 5Empty stringEmpty string - exampleString methods - example 1String methods - example 2String methods - example 3example 3 solutionexample 3 solution, cont.Exam question example Exam question - solutionMulti - dimensional arraysTwo - dimensional arraysTwo - dimensional arraysTwo - dimensional arraysDeclaring, Creating and InitializingLengths of Two-dimensional arraysLengths of Two-dimensional arraysLengths of Two-dimensional arrays, example.Lengths of Two-dimensional arrays, example.Lengths of Two-dimensional arrays, example.Slide Number 61Matrix addition and subtractionTwo - dimensional array example 1Two - dimensional array example 2Two - dimensional array example 2Two - dimensional array example 3Slide Number 67Two - dimensional array example 4Matrix multiplicationMatrix multiplication , cont.Puzzle
Top Related