CS101 - Algorithms & Programming I

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Advertisements

Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
1 Various Methods of Populating Arrays Randomly generated integers.
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
CSM-Java Programming-I Spring,2005 String Handling Lesson - 6.
ECE122 L13: Arrays of Objects March 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 13 Arrays of Objects.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
CMPE-013/L: “C” Programming Gabriel Hugh Elkaim – Spring 2013 CMPE-013/L Arrays and Strings Gabriel Hugh Elkaim Spring 2013.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Recursion & Collections API Recursion Revisited Programming Assignments using the Collections API.
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
Chapter 7 Arrays. © 2004 Pearson Addison-Wesley. All rights reserved7-2 Arrays Arrays are objects that help us organize large amounts of information Chapter.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings.
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
From C++ to Java A whirlwind tour of Java for C++ programmers.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
Textbook: Data Structures and the Java Collections Framework 3rd Edition by William Collins William Collins.
CSE 501N Fall ‘09 08: Arrays 22 September 2009 Nicholas Leidenfrost.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 7 Arrays 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
String Handling StringBuffer class character class StringTokenizer class.
Chapter 3A Strings. Using Predefined Classes & Methods in a Program To use a method you must know: 1.Name of class containing method (Math) 2.Name of.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples:
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 The if-else Statement An else clause can be added to an if statement to make an if-else statement.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
More on Arrays Review of Arrays of ints, doubles, chars
Lecture 5 array declaration and instantiation array reference
Arrays of Objects October 9, 2006 ComS 207: Programming I (in Java)
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Strings.
Array, Strings and Vectors
EKT 472: Object Oriented Programming
String and String Buffers
Building Java Programs Chapter 7
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Can store many of the same kind of data together
Java Coding 6 – part2 David Davenport Computer Eng. Dept.,
Recursion Problems.
Dr. Sampath Jayarathna Cal Poly Pomona
Visual Programming COMP-315
Object Oriented Programming
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
Arrays of Objects October 8, 2007 ComS 207: Programming I (in Java)
In Java, strings are objects that belong to class java.lang.String .
Arrays.
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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