CS1101: Programming Methodology

Slides:



Advertisements
Similar presentations
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.
Advertisements

Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Programming with Collections Collections in Java Using Arrays Week 9.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
Arrays. A group of data with same type stored under one variable. It is assumed that elements in that group are ordered in series. In C# language arrays.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
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.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
C++ for Engineers and Scientists Third Edition
Chapter 7 & 8- Arrays and Strings
Chapter 8 Arrays and Strings
Chapter 7. 2 Objectives You should be able to describe: The string Class Character Manipulation Methods Exception Handling Input Data Validation Namespaces.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
CS1101: Programming Methodology Aaron Tan.
CS1101: Programming Methodology
CS1101: Programming Methodology Aaron Tan.
Java Unit 9: Arrays Declaring and Processing Arrays.
CS1101: Programming Methodology Aaron Tan.
CS1101: Programming Methodology
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Lists in Python.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
Chapter 8 Arrays and Strings
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
CS1101: Programming Methodology Aaron Tan.
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.
Fundamental Programming: Fundamental Programming Introduction to C++
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
CS1101: Programming Methodology
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
CS1101: Programming Methodology Aaron Tan.
CS1101: Programming Methodology
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Java’s String Class.
Array Objectives To understand the concept of arrays To understand the purpose to which we use arrays. To be able to declare references to arrays. To be.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Arrays Chapter 13 How to do the following with a one dimensional array: Declare it, use an index.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
CS1020 Data Structures and Algorithms I Lecture Note #2 Arrays.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
CS1101: Programming Methodology
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
int [] scores = new int [10];
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
 2005 Pearson Education, Inc. All rights reserved Arrays.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Chapter VII: Arrays.
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.
Building Java Programs
Presentation transcript:

CS1101: Programming Methodology

Week 8: Strings and Arrays  Previous lecture:  Chapter 7: Defining Your Own Classes – Part 2  This week:  Chapter 9: Characters and Strings  Chapter 10: Arrays and Collections  Next week:  Chapter 10: Arrays and Collections (cont’d)  Chapter 8: Exceptions © CS1101 (AY Semester 1)Week8 - 2

Chapter 9 Characters and Strings Let’ go over Thomas Wu’s slides now… © CS1101 (AY Semester 1)Week8 - 3

Quizzes Are 'A' and "A" the same thing? Why? Can char be used in a switch statement? How about a String object? Show the results, or if it is illegal, how to correct it. (ASCII value of 'a' is 97.) 1. System.out.println('a' + "xyz"); 2. System.out.println('a' + 123); 3. System.out.println('a' + 'b'); 4. if ("a" < "b") if ("abc" < "xx")... © CS1101 (AY Semester 1)Week

Do not overuse String Some students like to use String to solve numerical problems, because there are so many methods available for String.  For example, given an integer, extract its individual digits.  No good: convert the integer to a string, use substring to extract the individual characters, then convert each character to a digit.  Better: use division (/) and modulo (%), like what we did for Matriculation check code. Manipulating strings can use up a lot of space, due to its immutability. Strings are special. There are two ways to create a String object: with or without using ‘new’ statement. © CS1101 (AY Semester 1)Week8 - 5

Two ways of creating String objects © CS1101 (AY Semester 1)Week8 - 6 We can do this because String objects are immutable.

String: Effect of Immutability Example 1: String s = "abc"; s = s + "def";  A new string "abcdef" is created for s in the second statement. (Hence, it uses more memory. What happens to the memory space that stores "abc"?) Example 2: String s1 = "abc"; String s2 = "abc"; s1 = "xyz";  String s2 still refers to "abc". (Imagine the horror if this is not so!) Hence, String objects behave differently from other objects or arrays. © CS1101 (AY Semester 1)Week8 - 7

Exercise: Counting “the” (1/2) Write a program Ch9CountThe.java to count the number of times user entered the word “the”. The program ends when the user enters an empty string. The word “the” may be entered with leading or/and trailing spaces, and it may contain uppercase or lowercase letter. (This question is the same as question 1 in Week 9’s discussion.) © CS1101 (AY Semester 1)Week8 - 8

Exercise: Counting “the” (2/2) A sample run:  User’s inputs are shown in blue  Space is denoted by the character © CS1101 (AY Semester 1)Week8 - 9 Enter a string: tHe Enter a string: quick Enter a string: Enter a string: THE Enter a string: thE Enter a string: Number of times "the" appears: 3 Look up the String API page for appropriate String methods to use.String API page

Take-home lab assignment #4 It has been released more than a week ago. Deadline is Monday, 12 October 2009, 23:59hr. Any questions? © CS1101 (AY Semester 1)Week8 - 10

Motivation (1/3) Task: Find the minimum value of 3 integers int min; if ( (value1 <= value2) && (value1 <= value3) ) min = value1; else if ( (value2 <= value1) && (value2 <= value3) ) min = value2; else if ( (value3 <= value1) && (value3 <= value2) ) min = value3; What if the list is big?  Code will be longer – the logical expression in each ‘if’ statement will be longer and more complex. © CS1101 (AY Semester 1)Week8 - 11

Motivation (2/3) Consider this algorithm int min = value1; if (value2 < min) min = value2; if (value3 < min) min = value3; What if the list is big?  Code will still be longer, but if we make use of the regular pattern and the array structure for the data, we can ‘roll’ the if statements into a loop. © CS1101 (AY Semester 1)Week8 - 12

Motivation (3/3) Using the array structure int min = value[0]; if (value[1] < min) min = value[1]; if (value[2] < min) min = value[2]; Rolling into a loop using array subscript/index: int min = value[0]; for (int k = 1; k < 3; k++) { if (value[k] < min) min = value[k]; } The above code can be easily modified for a bigger list. © CS1101 (AY Semester 1)Week8 - 13

Chapter 10 Arrays and Collections (1/2) In computer science, we deal with very large amount of data  Eg: 3000 integers, 265 days, 1 million real numbers.  Do you want to create so many variables in your program? If the data are homogeneous (of the same type), we can organise them into a single collection (we normally call it a list). Array is an implementation of a list. It is an indexed collection of homogeneous data. © CS1101 (AY Semester 1)Week8 - 14

Chapter 10 Arrays and Collections (2/2) We will cover up to one-dimensional arrays today, and continue from two-dimensional arrays next week. The syntax for array is very simple, yet learning it allows us to solve many interesting problems. Let’ go over Thomas Wu’s slides now… © CS1101 (AY Semester 1)Week8 - 15

Array Declaration Syntax  Array declaration syntax: [] ; Example: double[] values;  Alternative syntax: []; Example: double values[];  I prefer the first one, it’s more readable and meaningful. The second form is more commonly used by C/C++ programmers. © CS1101 (AY Semester 1)Week8 - 16

Basic Terminology  An array is a form of ordered list.  A list is composed of elements.  List is homogeneous – elements are of the same base type.  Elements in a list have a common name.  The list as a whole is referenced through the common name.  Elements are referenced by subscripting (indexing) the common name. © CS1101 (AY Semester 1)Week8 - 17

Java Array Features  Subscripts/indices are denoted as expressions within square brackets [ ]  Size of array (number of elements) can be specified at run time  Index type is integer and index range must be 0 … n- 1 where n is the array size  Automatic bounds checking  Array is an object  Has features common to all other objects © CS1101 (AY Semester 1)Week8 - 18

Common mistake: length() vs length Do not mix up the two  The length of a String object str is obtained by calling the String method length()  Example: str.length()  The length (size) of an array arr is stored in its data member length  Example: arr.length © CS1101 (AY Semester 1)Week8 - 19

Classic Array Problems  Compute statistics (sum, mean, standard deviation, etc.) of the values in an numeric array.  Find the maximum (or minimum) value in an array.  Search for a value in an array.  Sort the values in an array.  Others © CS1101 (AY Semester 1)Week8 - 20

Loading an Array  Before we solve a problem involving array, we need to first load values into the array!  If you know the values before-hand, use array element initialization  Eg: int[] numbers = { 3, 7, -12, 8, 7 };  Slide 9 of Chapter 10  If not, you need to read the values from the user  Use a loop to read in the values  Slides 6-7 and 16 of Chapter 10  (If the array is large, the amount of data will be huge. We may need a file to store the data. We will learn how to read data from a file some other time.) © CS1101 (AY Semester 1)Week8 - 21

Exercise 1: Summing an Array  Write a program SumArray.java to compute the sum of all the values in an array containing type double values. Display the sum in 3 decimal places.  Let’s do it into 2 phases: load the array with values first, then compute the sum. (Instead of accumulating the sum as we load the array.) © CS1101 (AY Semester 1)Week Size of array: 10 Enter 10 values: The sum is  Download SumArray.java from course website, “Resources – Lectures” page.

Exercise 2: Finding Maximum  Write a program FindMax.java to find the largest value in an integer array. (Assume there is at least one element in the array.) © CS1101 (AY Semester 1)Week Size of array: 5 Enter 5 values: The largest value is 79  Take home exercise: What if you want to report the index of the largest value, instead of the value itself? (This problem is not well-defined! Why?) Size of array: 5 Enter 5 values: The largest value is at index 3

Very Common Mistake #1 Array Index Out of Range  Beware of ArrayIndexOutOfBoundsException. © CS1101 (AY Semester 1)Week public static void main(String[] args) { int numbers = new int[10];... for (int i=1; i<=numbers.length; i++) System.out.println(numbers[i]); }

Modular Programming Revisit “Modularize” SumArray.java and FindMax.java so that the computation of sum or maximum is performed in a method. Call your new programs SumArrayModular.java and FindMaxModular.java. © CS1101 (AY Semester 1)Week8 - 25

Exercise 3: Coin Change Download the file Ch3CoinChange.java from the course website, “Resources – Lectures”. Rewrite it using an array of coin denominations ( int[] coins ). Name your program Ch10CoinChange.java. Modularize your program by writing a method computeCoins().  What is its return type?  Does it have any argument(s)? If so, what is/are the type(s) of its argument(s)? © CS1101 (AY Semester 1)Week8 - 26

Exercise 4: Array of Points (Take-home) (1/2) Write a program Ch10PointArray.java to create an array of Point objects, and find out which point in the array is furthest from the origin. If there are more than one such furthest point, output the smallest index among them. You may assume that the array contains at least one point. © CS1101 (AY Semester 1)Week8 - 27

Exercise 4: Array of Points (Take-home) (2/2) Sample output: © CS1101 (AY Semester 1)Week Enter number of points: 5 Enter coordinates for point #0: Enter coordinates for point #1: 1 4 Enter coordinates for point #2: 4 -3 Enter coordinates for point #3: 0 5 Enter coordinates for point #4: -1 1 The furthest point is at index 2

Very Common Mistake #2 (1/2) When you have an array of objects, it’s very common to forget to instantiate the array’s objects. Programmers often instantiate the array itself and then think they’re done – that leads to java.lang.NullPointerException. © CS1101 (AY Semester 1)Week8 - 29

Very Common Mistake #2 (2/2) © CS1101 (AY Semester 1)Week Point[] array = new Point[3]; for (int i=0; i<array.length; i++) { array[i].setLocation(1,2); } array null There are no objects referred to by array[0], array[1], and array[2]! Point[] array = new Point[3]; for (int i=0; i<array.length; i++) { array[i] = new Point(); array[i].setLocation(1,2); } Corrected code: array 0 x 0 y 0 x 0 y x 0 0 y 2 1

Method main() (1/2) Now that we have learned array, let’s check out the main() method. Usual header for main() method: public static void main(String[] args)  args is an array of String objects. Download Ch10MainDemo.java: © CS1101 (AY Semester 1)Week public class Ch10MainDemo { public static void main(String[] args) { for (int i=0; i<args.length; i++) System.out.println("args[" + i + "]: " + args[i]); }

Method main() (2/2) This allows user to specify command line arguments when executing the program. java Ch10MainDemo 10 ABC-D hello "Ice cream" Output: © CS1101 (AY Semester 1)Week args[0]: 10 args[1]: ABC-D args[2]: hello args[3]: Ice cream

Summary for Today Characters and Strings  More String methods  Patterns (regular expressions) Arrays  Syntax of one-dimensional array  Creating and using an array  Passing array into a method © CS1101 (AY Semester 1)Week8 - 33

Announcements/Things-to-do (1/2) Complete the following  Ch10PointArray.java Take-home lab #4 Deadline: 12 October 2009, Monday, 23:59hr To prepare for next lecture  We will continue with 2-dimensional arrays and ArrayList next week.  Read Chapters 10 and 8 and their PowerPoint files before you come for lecture.  We will skip Map for Chapter 10, and Assertions for Chapter 8. © CS1101 (AY Semester 1)Week8 - 34

Announcements/Things-to-do (2/2) Sit-in Lab #2  To be conducted during this week’s discussion session.  Please be punctual.  Make-up lab will only be allowed if you miss the lab with valid reason and proof.  Topics tested include everything up to Chapter 7.  Sit-in lab #2 constitute 5% of your final grade. © CS1101 (AY Semester 1)Week8 - 35

End of File © CS1101 (AY Semester 1)Week8 - 36