Arrays An array is a group of contiguous

  • Slides: 35
Download presentation
Arrays • An array is a group of contiguous locations that all have the

Arrays • An array is a group of contiguous locations that all have the same name and the same type. x 5 x[0] -2 x[1] 8 3 x[2] -2 7 x[3] x[4] x[5] • Accessing array elements: arrayname[index] where index is an integer expression x[0]=2; i=2; x[i+1]=x[i]; 6/12/2021 CS 101 - Algorithms & Programming I 1

Arrays (cont. ) • The values held in an array are called array elements

Arrays (cont. ) • The values held in an array are called array elements • An array stores multiple values of the same type – the element type • The element type can be a primitive type or an object reference – Therefore, we can create an array of integers, an array of characters, an array of String objects, etc. • In Java, the array itself is an object that must be instantiated 6/12/2021 CS 101 - Algorithms & Programming I 2

Arrays (cont) • Another way to depict an array: scores 79 87 94 82

Arrays (cont) • Another way to depict an array: scores 79 87 94 82 67 98 87 81 74 91 6/12/2021 CS 101 - Algorithms & Programming I 3

Declaring and Allocating Arrays type[] arrayname = new type[arraysize]; int[] x; x = new

Declaring and Allocating Arrays type[] arrayname = new type[arraysize]; int[] x; x = new int[8]; int[] y = new int[10]; type[] arrayname = { values }; int[] y = {1, 3, 5, 8}; allocates an integer array with size 4 (index range: 0 -3) with initial values. Other Notation: type arrayname[]; int x[]; We prefer the first notation because it is consistent with other declarations. Array Length: x. length 6/12/2021 arrayname. length 8 CS 101 - Algorithms & Programming I 4

Bounds Checking • Once an array is created, it has a fixed size •

Bounds Checking • Once an array is created, it has a fixed size • An index used in an array reference must specify a valid element – the index value for an array with size n must be in range 0 to n-1 – if the array codes can hold 100 values, it can be indexed using only the numbers 0 to 99 – The Java interpreter throws an Array. Index. Out. Of. Bounds. Exception if an array index is out of bounds ( bounds checking ) – It’s common to introduce off-by-one errors when using arrays for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon; • Each array object has a public constant called length that stores the size of the array – It is referenced using the array name: scores. length – Note that length holds the number of elements, not the largest index 6/12/2021 CS 101 - Algorithms & Programming I 5

Array -- Examples Reading values of an int array: int[] x = new int[100];

Array -- Examples Reading values of an int array: int[] x = new int[100]; for (i=0; i<x. length; i++) System. out. println(“Enter an integer: “); x[i] = scan. next. Int(); } Shifting values of an int array: int temp = x[0]; for (i=0; i<x. length-1; i++) x[i]=x[i+1]; x[x. length-1]=temp; 6/12/2021 CS 101 - Algorithms & Programming I 6

Array – Examples (cont. ) Finding the location of the maximum value in an

Array – Examples (cont. ) Finding the location of the maximum value in an int array: int loc = 0; for (i=1; i<x. length; i++) if(x[i]>x[loc]) loc=i; Finding the first location of a given value in an int array: int loc, i=0; while ((i<x. length) && (x[i]!=item)) i=i+1; if (i>=x. length) loc=-1; // not found else loc=i; // found 6/12/2021 CS 101 - Algorithms & Programming I 7

Array – Examples (cont. ) Finding summation of the values in an int array:

Array – Examples (cont. ) Finding summation of the values in an int array: int sum=0; for (i=0; i<x. length; i++) sum=sum+x[i]; Reversing the contents of an int array: int temp, i, j; for (i=0, j=x. length-1; i<j; i++, j--) { temp=x[i]; x[i]=x[j]; x[j]=temp; } 6/12/2021 CS 101 - Algorithms & Programming I 8

Passing Arrays to Methods • Since arrays are also objects, they are passed into

Passing Arrays to Methods • Since arrays are also objects, they are passed into method by call-by-reference. • A pointer to the array is passed into the method. • The contents of the array pointed by an actual parameter can be changed by the method. static void m(int[] x) { int i, temp; temp=x[0]; for (i=0; i<(x. length-1); i++) x[i]=x[i+1]; x[x. length-1]=temp; } // in main int[] a = {3, 5, 7, 8}; m(a); // the content of a will be changed by m 6/12/2021 CS 101 - Algorithms & Programming I 9

Passing Arrays into Methods -- Example static void findprimes(int[] p, int n) { int

Passing Arrays into Methods -- Example static void findprimes(int[] p, int n) { int i, val; p[0]=2; val=3; i=1; while (i<n) { if (isprime(val, p, i)) { p[i]=val; i++; } val=val+1; } } static boolean isprime(int v, int[] p, int lastprimeloc) { boolean primeflag=true; int i=0; while (primeflag && (i<lastprimeloc)) if (v%p[i] == 0) primeflag=false; else i++; return primeflag; } 6/12/2021 CS 101 - Algorithms & Programming I 10

Passing Arrays into Methods – Example (cont. ) // in main int i; int[]

Passing Arrays into Methods – Example (cont. ) // in main int i; int[] primes = new int[100]; findprimes(primes, 10); System. out. println(“First 10 Primes: ”); for (i=0; i<10; i++) System. out. println(primes[i]); 6/12/2021 CS 101 - Algorithms & Programming I 11

Arrays of Objects • The elements of an array can be object references •

Arrays of Objects • The elements of an array can be object references • The following declaration reserves space to store 5 references to String objects String[] words = new String[5]; • It does NOT create the String objects themselves • Initially an array of objects holds null references • Each object stored in an array must be instantiated separately 6/12/2021 CS 101 - Algorithms & Programming I 12

Arrays of Objects • The words array when initially declared: words - • At

Arrays of Objects • The words array when initially declared: words - • At this point, the following reference would throw a Null. Pointer. Exception: System. out. println (words[0]); 6/12/2021 CS 101 - Algorithms & Programming I 13

Arrays of Objects • After some String objects are created and stored in the

Arrays of Objects • After some String objects are created and stored in the array: “friendship” words “loyalty” “honor” - words[0] = “friendship”; words[1] = “loyalty”; words[2] = “honor”; 6/12/2021 CS 101 - Algorithms & Programming I 14

Arrays of Objects • Keep in mind that String objects can be created using

Arrays of Objects • Keep in mind that String objects can be created using literals • The following declaration creates an array object called verbs and fills it with four String objects created using string literals String[] verbs = {"play", "work", "eat", "sleep"}; 6/12/2021 CS 101 - Algorithms & Programming I 15

Multi-Dimensional Arrays • Allocation of two-dimensional array: int[][] x = new int[5][3]; • Accessing

Multi-Dimensional Arrays • Allocation of two-dimensional array: int[][] x = new int[5][3]; • Accessing elements of a two-dimensional array: x[0][0] = 5; • Initializing a two-dimensional array: int[][] a = {{3, 5, 7}, {8, 6, 9}}; 6/12/2021 CS 101 - Algorithms & Programming I 16

Multi-Dimensional Arrays -- Example // An, m* Bm, k Cn, k public static void

Multi-Dimensional Arrays -- Example // An, m* Bm, k Cn, k public static void matrixmult(int[][] a, int[][] b, int[][] c, int n, int m, int k) { int i, j, p; for (i=0; i<n; i++) for (j=0; j<k; j++) { c[i][j]=0; for (p=0; p<m; p++) c[i][j]=c[i][j] + a[i][p] * b[p][j]; } } 6/12/2021 CS 101 - Algorithms & Programming I 17

Arrays of -Varying Length • The size of each row of a two-dimensional array

Arrays of -Varying Length • The size of each row of a two-dimensional array can be different; int[][] x; x = new int[5][]; x[0] = new int[1]; x[1] = new int[2]; x[2] = new int[3]; x[3] = new int[4]; x[4] = new int[5]; x. length x[0]. length x[1]. length ? x 5 1 2 x[1] = new int[10]; 6/12/2021 CS 101 - Algorithms & Programming I 18

Different Types for Arrays String[] names = {“john”, ”mark”, ”mary”, ”cindy”}; boolean[] bvals =

Different Types for Arrays String[] names = {“john”, ”mark”, ”mary”, ”cindy”}; boolean[] bvals = new boolean[10]; char[] charray = {‘i’, ’l’, ’y’, ’a’, ’s’}; char array is not a string. Reading 100 names from the keyboard: String[] names = new String[100]; for (i=0; i<100; i++) names[i] = scan. next. Line(); 6/12/2021 CS 101 - Algorithms & Programming I 19

String and char Array • Strings in Java are not char arrays (in C

String and char Array • Strings in Java are not char arrays (in C and C++ strings are char arrays). • But, we convert a char array into a string or a string into a char array into string: char[] name = {‘m’, ’a’, ’r’, ’k’}; String aname = new String(name}; string into char array: String aname = “mary”; char[] name = aname. to. Char. Array(); 6/12/2021 CS 101 - Algorithms & Programming I 20

Strings • A string is a sequence of characters. • Java provides two classes

Strings • A string is a sequence of characters. • Java provides two classes to support strings: – String class – the instances of String class are constants, ie. the content of a String object cannot be changed after its creation. – String. Buffer class – the instances of String. Buffer class are mutable, ie. the content of a String. Buffer object can be changed after its creation. • The String class has some unique privileges not shared by ordinary classes. – A string can be created using string literals. – Operator + can be applicable to strings. • The characters in a string indexed by 0 to n-1, where n is the length of the string. Spring 2003 COP 3330 Object Oriented Programming 21

String Class • Creation of a String object. String s = new String(“abc”); String

String Class • Creation of a String object. String s = new String(“abc”); String s = “abc”; • Add operator: String s 1 = “abc”; String s 2 = “de”; String s 3 = s 1 + s 2; • String class has a lot of methods. These methods are useful to manipulate strings. 6/12/2021 CS 101 - Algorithms & Programming I 22

length and char. At int length() – this instance method returns the length of

length and char. At int length() – this instance method returns the length of the string. String s=“abc”; s. length() returns 3 char. At(int index) – this instance method returns the character at the given index. String s=“abcde”; s. length(); s. char. At(0); s. char. At(1); s. char. At(4); s. char. At(5); 6/12/2021 5 ‘a’ ‘b’ ‘e’ error CS 101 - Algorithms & Programming I 23

index. Of int index. Of(char c) int index. Of(char c, int index) Returns the

index. Of int index. Of(char c) int index. Of(char c, int index) Returns the index of the first occurrence of the character c in the current object, no less than index (default 0). Returns – 1 if there is no such occurrence. String s=“ababc”; s. index. Of(‘b’) s. index. Of(‘b’, 2) 1 3 int index. Of(String s 2) int index. Of(String s 2, int index) Returns the index of the first occurrence of the string s 2 in the current object, no less than index (default 0). Returns – 1 if there is no such occurrence. String s=“daabcabc”; String s 2=“ab”; s. index. Of(s 2) 2 s. index. Of(s 2, 3) 5 6/12/2021 CS 101 - Algorithms & Programming I 24

substring String substring(int startindex) String substring(int startindex, int lastindex) Returns the substring of the

substring String substring(int startindex) String substring(int startindex, int lastindex) Returns the substring of the current object starting from startindex and ending with lastindex-1 (or the last index of the string if lastindex is not given) String s=“abcdef”; s. substring(1) s. substring(3) s. substring(1, 4) s. substring(3, 5) 6/12/2021 “bcdef” “bcd” “de” CS 101 - Algorithms & Programming I 25

equals and equals. Ignore. Case boolean equals(String s 2) boolean equals. Ignore. Case(String s

equals and equals. Ignore. Case boolean equals(String s 2) boolean equals. Ignore. Case(String s 2) Returns true if the current object is equal to s 2; otherwise false. equals. Ignorecase disregards the case of the characters. String s=“abc”; s. equals(“abc”) s. equals(“abcd”) s. equals(“a. Bc”) s. equals. Ignore. Case(“a. Bc”) 6/12/2021 true false true CS 101 - Algorithms & Programming I 26

String. Buffer Class • String. Buffer constructors: String. Buffer() String. Buffer(int size) Returns an

String. Buffer Class • String. Buffer constructors: String. Buffer() String. Buffer(int size) Returns an instance of the String. Buffer class that is empty but has an initial capacity of size characters (default 16 characters). String. Buffer(String arg) Creates an instance of the String. Buffer class from the string arg. • length and char. At methods are also defined for String. Buffer class. 6/12/2021 CS 101 - Algorithms & Programming I 27

append and insert String. Buffer append(String s) Returns the current object with the String

append and insert String. Buffer append(String s) Returns the current object with the String parameter s appended to the end. String. Buffer insert(int index, char c) String. Buffer insert(int index, String s) Inserts the character c (or String s) into the current String. Buffer object at index. The characters (after index) are shifted to right. String. Buffer sb = new String. Buffer(“abcd”); sb. insert(0, ”AB”) sb is “ABabcd” sb. insert(1, ”CD”) sb is “ACDBabcd” sb. insert(8, ”EFG”) sb is “ACDBabcd. EFG” sb. append(“HI”) 6/12/2021 sb is “ACDBabcd. EFGHI” CS 101 - Algorithms & Programming I 28

Palindrome Example import java. io. *; public class Palindrome { static boolean is. Palindrome(String

Palindrome Example import java. io. *; public class Palindrome { static boolean is. Palindrome(String s) { int i = 0; int j = s. length() - 1; boolean flag = true; while ((i<j) && flag){ if (s. char. At(i) != s. char. At(j)) flag = false; else {i++; j--; } } return flag; } 6/12/2021 CS 101 - Algorithms & Programming I 29

Palindrome Example (cont. ) public static void main(String args[]) throws IOException { String s;

Palindrome Example (cont. ) public static void main(String args[]) throws IOException { String s; Scanner scan = new Scanner(System. in); System. out. print("A String > "); s = scan. next. Line(); if (is. Palindrome(s)) System. out. println(s + " is a palindrome"); else System. out. println(s + " is not a palindrome"); } } 6/12/2021 CS 101 - Algorithms & Programming I 30

Decimal to Binary -- Example import java. util. *; public class Dec. To. Binary

Decimal to Binary -- Example import java. util. *; public class Dec. To. Binary { static String. Buffer to. Binary(int dec. Val) { String. Buffer sb = new String. Buffer(""); if (dec. Val == 0) sb. insert(0, "0"); else while (dec. Val != 0) { if (dec. Val%2 == 0) sb. insert(0, "0"); else sb. insert(0, "1"); dec. Val = dec. Val / 2; } return sb; } 6/12/2021 CS 101 - Algorithms & Programming I 31

Decimal to Binary – Example (cont. ) public static void main(String args[]) { int

Decimal to Binary – Example (cont. ) public static void main(String args[]) { int num; Scanner scan = new Scanner(System. in); System. out. print("An integer > "); num = scan. next. Int() System. out. println("Decimal Number: " + num + " Corresponding Binary Number: " + to. Binary(num)); } } 6/12/2021 CS 101 - Algorithms & Programming I 32

Searching • Search the first n elements of x for a target value &

Searching • Search the first n elements of x for a target value & return its location if found, else -1 public static int search(int n, int[] x, int target) { int pos = 0; while ( pos < n && x[pos] != target) pos++; if ( x[pos] == target) return pos; // found at pos else return – 1; // not found } Sequential search O(n) 6/12/2021 CS 101 - Algorithms & Programming I 33

Sorting • Selection sort 5 4 1 7 3 9 5 9 1 7

Sorting • Selection sort 5 4 1 7 3 9 5 9 1 7 3 4 n=6 + n=5 5 4 1 3 7 9 + n=4 3 4 1 5 7 9 + n=3 Sum = n. ( n +1) / 2 = n 2/2 + n/2 6/12/2021 CS 101 - Algorithms & Programming I 3 1 4 5 7 9 + n=2 1 3 4 5 7 9 + n=1 O( n 2) 34

Selection Sort • To sort first n elements of array X while n >

Selection Sort • To sort first n elements of array X while n > 1 find location of max value in first n elements of X swap element at location of max with element at n-1 decrement n tmp 9 grades 6/12/2021 5 9 3 1 7 3 9 0 1 2 3 4 CS 101 - Algorithms & Programming I swap( int i, int j) { int tmp; tmp = X[i]; X[i} = X[j]: X[j] = tmp; } 35