Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS101 - Algorithms & Programming I

Similar presentations


Presentation on theme: "CS101 - Algorithms & Programming I"— Presentation transcript:

1 CS101 - Algorithms & Programming I
Arrays An array is a group of contiguous locations that all have the same name and the same type. x x[0] x[1] x[2] 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]; 5 -2 8 3 7 5/1/2019 CS101 - Algorithms & Programming I

2 CS101 - Algorithms & Programming I
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 5/1/2019 CS101 - Algorithms & Programming I

3 CS101 - Algorithms & Programming I
Arrays (cont) Another way to depict an array: scores 79 87 94 82 67 98 81 74 91 5/1/2019 CS101 - Algorithms & Programming I

4 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: arrayname.length x.length  8 5/1/2019 CS101 - Algorithms & Programming I

5 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 ArrayIndexOutOfBoundsException if an array index is out of bounds ( bounds checking ) It’s common to introduce off-by-one errors when using arrays 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 for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon; 5/1/2019 CS101 - Algorithms & Programming I

6 CS101 - Algorithms & Programming I
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.nextInt(); } 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; 5/1/2019 CS101 - Algorithms & Programming I

7 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 5/1/2019 CS101 - Algorithms & Programming I

8 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; } 5/1/2019 CS101 - Algorithms & Programming I

9 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 5/1/2019 CS101 - Algorithms & Programming I

10 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; 5/1/2019 CS101 - Algorithms & Programming I

11 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]); 5/1/2019 CS101 - Algorithms & Programming I

12 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 5/1/2019 CS101 - Algorithms & Programming I

13 Arrays of Objects The words array when initially declared:
- At this point, the following reference would throw a NullPointerException: System.out.println (words[0]); 5/1/2019 CS101 - Algorithms & Programming I

14 CS101 - Algorithms & Programming I
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”; 5/1/2019 CS101 - Algorithms & Programming I

15 CS101 - Algorithms & Programming I
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"}; 5/1/2019 CS101 - Algorithms & Programming I

16 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}}; 5/1/2019 CS101 - Algorithms & Programming I

17 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]; } 5/1/2019 CS101 - Algorithms & Programming I

18 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  5 x[0].length  1 x[1].length  2 ? x[1] = new int[10]; x 5/1/2019 CS101 - Algorithms & Programming I

19 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.nextLine(); 5/1/2019 CS101 - Algorithms & Programming I

20 CS101 - Algorithms & Programming I
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. 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.toCharArray(); 5/1/2019 CS101 - Algorithms & Programming I

21 COP 3330 Object Oriented Programming
May 1, 2019 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. StringBuffer class – the instances of StringBuffer class are mutable, ie. the content of a StringBuffer 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

22 CS101 - Algorithms & Programming I
String Class Creation of a String object. String s = new String(“abc”); String s = “abc”; Add operator: String s1 = “abc”; String s2 = “de”; String s3 = s1 + s2; String class has a lot of methods. These methods are useful to manipulate strings. 5/1/2019 CS101 - Algorithms & Programming I

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

24 CS101 - Algorithms & Programming I
indexOf int indexOf(char c) int indexOf(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.indexOf(‘b’)  1 s.indexOf(‘b’,2)  3 int indexOf(String s2) int indexOf(String s2, int index) Returns the index of the first occurrence of the string s2 in the current object, no less than index (default 0). Returns –1 if there is no such occurrence. String s=“daabcabc”; String s2=“ab”; s.indexOf(s2)  2 s.indexOf(s2,3)  5 5/1/2019 CS101 - Algorithms & Programming I

25 CS101 - Algorithms & Programming I
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)  “bcdef” s.substring(3)  “def” s.substring(1,4)  “bcd”  s.substring(3,5)  “de”  5/1/2019 CS101 - Algorithms & Programming I

26 equals and equalsIgnoreCase
boolean equals(String s2) boolean equalsIgnoreCase(String s2) Returns true if the current object is equal to s2; otherwise false. equalsIgnorecase disregards the case of the characters. String s=“abc”; s.equals(“abc”)  true s.equals(“abcd”)  false s.equals(“aBc”)  false s.equalsIgnoreCase(“aBc”)  true 5/1/2019 CS101 - Algorithms & Programming I

27 CS101 - Algorithms & Programming I
StringBuffer Class StringBuffer constructors: StringBuffer() StringBuffer(int size) Returns an instance of the StringBuffer class that is empty but has an initial capacity of size characters (default 16 characters). StringBuffer(String arg) Creates an instance of the StringBuffer class from the string arg. length and charAt methods are also defined for StringBuffer class. 5/1/2019 CS101 - Algorithms & Programming I

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

29 CS101 - Algorithms & Programming I
Palindrome Example import java.io.*; public class Palindrome { static boolean isPalindrome(String s) { int i = 0; int j = s.length() - 1; boolean flag = true; while ((i<j) && flag){ if (s.charAt(i) != s.charAt(j)) flag = false; else {i++; j--; } } return flag; 5/1/2019 CS101 - Algorithms & Programming I

30 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.nextLine(); if (isPalindrome(s)) System.out.println(s + " is a palindrome"); else System.out.println(s + " is not a palindrome"); } 5/1/2019 CS101 - Algorithms & Programming I

31 Decimal to Binary -- Example
import java.util.*; public class DecToBinary { static StringBuffer toBinary(int decVal) { StringBuffer sb = new StringBuffer(""); if (decVal == 0) sb.insert(0,"0"); else while (decVal != 0) { if (decVal%2 == 0) sb.insert(0,"1"); decVal = decVal / 2; } return sb; 5/1/2019 CS101 - Algorithms & Programming I

32 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.nextInt() System.out.println("Decimal Number: " + num + " Corresponding Binary Number: " + toBinary(num)); } 5/1/2019 CS101 - Algorithms & Programming I

33 May 1, 2019 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 } Good problem to work out together in class before showing solution above note the solution here relies on short circuit boolean evaluation – solve without this too. Note that it is incorrect – can they see why/when it might fail? The if ( x[pos] == target) fails if n = x.length & could return the wrong answer in other cases if the target is the element at x[n] it should be if ( pos != n ) Contrast efficiency of sequential search with binary search (as provided by Java Collections framework.) Sequential search O(n) 5/1/2019 CS101 - Algorithms & Programming I

34 CS101 - Algorithms & Programming I
May 1, 2019 Sorting Selection sort 5 9 1 7 3 4 5 4 1 7 3 9 5 4 1 3 7 9 3 4 1 5 7 9 3 1 4 5 7 9 1 3 4 5 7 9 Explain selection sort Note efficiency is actual this –1 (since last step is unecesaary) & +k(n-1) for the swaps Contrast efficiency with that of mergesort provided by Collections framework which is O(log n). n=6 n=5 n=4 n=3 n=2 n=1 + Sum = n.( n +1) / 2 = n2/2 + n/2 O( n2) 5/1/2019 CS101 - Algorithms & Programming I

35 CS101 - Algorithms & Programming I
May 1, 2019 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 swap( int i, int j) { int tmp; tmp = X[i]; X[i} = X[j]: X[j] = tmp; } tmp 9 Find location of max is left as exercise! 9 1 7 3 5 2 4 grades 3 9 5/1/2019 CS101 - Algorithms & Programming I


Download ppt "CS101 - Algorithms & Programming I"

Similar presentations


Ads by Google