CS1101: Programming Methodology Aaron Tan
2 This is Week 6 Last week: Week 4’s Exercise 5 (Prime number) A mini programming test! Chapter 5: Using Pre-Built Methods Other classes: Random, DecimalFormat This week: Chapter 10: Arrays Only sections 10.1 to 10.6 We will cover the other sections some other time.
3 Arrays In computer science, we deal with very large amount of data. Eg: 3000 integers, 365 days, 1 million real numbers. Do you want to create so many variables? If the data are homogeneous (of the same type), we can group them into a single collection. Array is an indexed collection of homogeneous data. Let’s get to Chapter 10 now!
4 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.
5 Classic Array Problems Sum the values in an array. Find the maximum (or minimum) value in an array. Search for a value in an array. Sort the values in an array.
6 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 }; Slides 12 and 14 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 of Chapter 10 We will learn how to read data from a file some other time.
7 Exercise 1: Summing an Array Write a program SumArray.java to compute the sum of all the values in an array containing 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.) Size of array: 10 Enter 10 values: The sum is Download SumArray.java from course website, “Resources”, “Lectures” page.
8 Exercise 2: Finding maximum value Write a program FindMax.java to find the largest value in an integer array. (Assume there is at least one element in the array.) 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
9 Common Mistake: Index Out of Range Beware of ArrayIndexOutOfBoundsException. public static void main(String[] args) { int numbers = new int[10];... for (int i=1; i<=numbers.length; i++) System.out.println(numbers[i]); }
10 Modular Programming (1/5) As our problems get more complex, the main() method might get too long. It is advisable to split the problem into smaller sub- problems, and to write appropriate methods for the sub-problems. In general a problem is solved in 3 steps: input computation output. It is customary to write a separate method to perform the computation step. (If the computation is complex, it should be split further into smaller steps and each step performed by a method.)
11 Modular Programming (2/5) Download CheckNRIC.java program which we did before. Here’s the partial code: public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); System.out.print("Enter 7-digit NRIC number: "); int number = stdIn.nextInt(); int digit7, digit6, digit5, digit4, digit3, digit2, digit1, step1, step2, step3; char checkCode; // computation of check code - code omitted... System.out.println("Check code = " + checkCode); } These variables are used in the computation of the check code.
12 Modular Programming (3/5) ‘Modularizing’ CheckNRIC.java: public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); System.out.print("Enter 7-digit NRIC number: "); int number = stdIn.nextInt(); char checkCode; // computation of check code checkCode = generateCheckCode(number); System.out.println("Check code = " + checkCode); } Delegate the job to the method generateCheckCode(). Pass number into the method generateCheckCode(). What are you expecting generateCheckCode() to return? A character.
13 Modular Programming (4/5) How does generateCheckCode() method look like? public static char generateCheckCode(int num) { // Extract digits int digit7 = num%10; num /= 10; int digit6 = char code = return code; } The method returns a character. The method expects an integer argument. The return statement passes the character to the caller. Download NewCheckNRIC.java and compare it with CheckNRIC.java.
14 Modular Programming (5/5) Let’s see how we can “modularize” our programs for the previous two exercises. I will show you NewSumArray.java and NewFindMax.java.
15 Exercise 3: Coin Change Download the file CoinChange.java from the course website, “Resources”, “Lectures”. Rewrite it using an array of coin denominations ( int[] coins ). Name your program NewCoinChange.java. Modularize your program by writing a method computeCoins(). What is its return type? Does it have any argument? If so, what is the type of its argument?
16 Method main() (1/2) Now that we have learnt array, let’s check out the main() method. Usual signature for main() method: public static void main(String[] args) args is an array of String objects Consider this: public class Demo { public static void main(String[] args) { for (int i=0; i<args.length; i++) System.out.println("args[" + i + "]: " + args[i]); } // end main } end Demo
17 Method main() (2/2) This allows user to specify command line arguments when executing the program. java Demo 10 ABC-D hello "Ice Cream" Output: args[0]: 10 args[1]: ABC-D args[2]: hello args[3]: Ice Cream
18 Sorting and Searching I will be covering more topics in every lecture from now on to make up for the lost lecture on 27 October (Deepavali). Sorting Searching The above two topics are not included in the mid-term test.
19 Sorting Classic computer science problem Sort an array Three basic (but slow) sorting algorithms Selection sort Bubblesort Insertion sort Other faster sorting algorithms (covered in CS1102 and other advanced modules) Mergesort Quicksort Heapsort, etc.
20 Selection Sort (1/2) 1.Find the smallest element in the list min first exchange sorted unsorted This is the result of one pass. 2.Exchange the element in the first position and the smallest element. Now the smallest element is in the first position. 3.Repeat Step 1 and 2 with the list having one less element (i.e., the smallest element is discarded from further processing).
21 Selection Sort (2/2) sorted Pass # Result AFTER one pass is completed.
22 Bubble Sort (1/2) Algorithm Assume array is arr for (int i = arr.length – 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (arr[j] > arr[j+1] swap arr[j] with arr[j+1] } Can you write the code?
23 Bubble Sort (2/2) exchange ok exchange The largest value 90 is at the end of the list. Showing the first pass…
24 Searching Another classic computer science problem Search for a value in a list of items Two algorithms Sequential search (also called linear search) Binary search (applicable for sorted array) – much faster
25 Announcement/Reminder (1/2) Lab #2 Release: 16 September (Tuesday), 2359hr. Deadline: 1 October (Wednesday), 2359hr. Identical codes Please do not share codes for your lab assignments!
26 Announcement/Reminder (2/2) Consultation 24 September (Wednesday), 10am – 12nn. I will be in PL3. Mid-term test 4 October, Saturday, 12noon, LT15 (for CS1101X students) Refer to course website for more info:
27 This is Week 6 Next week? Recess! (Hooray!) The week after next? Chapter 6 Object-Oriented Programming (finally!) Mid-term test (argh!)
28 End of file