Title: CS1101: Programming Methodology http://www.comp.nus.edu.sg/~cs1101x/
1CS1101 Programming Methodology
http//www.comp.nus.edu.sg/cs1101x/
Aaron Tan
2This is Week 6
- Last week
- Week 4s 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.
3Arrays
- 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. - Lets get to Chapter 10 now!
4Array Declaration Syntax
- Array declaration syntax
- ltelement-typegt ltarray-variablegt
- Example double values
- Alternative syntax
- ltelement-typegt ltarray-variablegt
- Example double values
- I prefer the first one, its more readable and
meaningful. The second form is more commonly used
by C/C programmers.
5Classic 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.
6Loading 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 15-16 of Chapter 10
- We will learn how to read data from a file some
other time.
7Exercise 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. - Lets 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 5.1 16 3.2 1.8
-4 12.3 8 3.3 -2 9.1 The sum is 52.800
- Download SumArray.java from course website,
Resources, Lectures page.
8Exercise 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 10 -20 43 79 8
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 10 -20 43 79 8
The largest value is at index 3
9Common Mistake Index Out of Range
- Beware of ArrayIndexOutOfBoundsException.
public static void main(String args)
int numbers new int10 . . . for
(int i1 iltnumbers.length i)
System.out.println(numbersi)
10Modular 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.)
11Modular Programming (2/5)
- Download CheckNRIC.java program which we did
before. Heres 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)
12Modular 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)
Pass number into the method generateCheckCode().
Delegate the job to the method generateCheckCode()
.
What are you expecting generateCheckCode() to
return? A character.
13Modular Programming (4/5)
The method returns a character.
- How does generateCheckCode() method look like?
public static char generateCheckCode(int num)
// Extract digits int digit7
num10 num / 10 int digit6 ... ...
char code ... ... return code
The method expects an integer argument.
The return statement passes the character to the
caller.
- Download NewCheckNRIC.java and compare it with
CheckNRIC.java.
14Modular Programming (5/5)
- Lets see how we can modularize our programs
for the previous two exercises. - I will show you NewSumArray.java and
NewFindMax.java.
15Exercise 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?
16Method main() (1/2)
- Now that we have learnt array, lets 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 i0
iltargs.length i) System.out.println("ar
gs" i " " argsi) // end main
end Demo
17Method main() (2/2)
- This allows user to specify command line
arguments when executing the program. java Demo
10 ABC-D hello "Ice Cream" - Output
args0 10 args1 ABC-D args2
hello args3 Ice Cream
18Sorting 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.
19Sorting
- 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.
20Selection Sort (1/2)
- Find the smallest element in the list.
- Exchange the element in the first position and
the smallest element. Now the smallest element is
in the first position.
- Repeat Step 1 and 2 with the list having one less
element (i.e., the smallest element is discarded
from further processing).
This is the result of one pass.
21Selection Sort (2/2)
Result AFTER one pass is completed.
2
3
7
8
22Bubble Sort (1/2)
Assume array is arr for (int i arr.length 1
i gt 0 i--) for (int j 0 j lt i j)
if (arrj gt arrj1 swap
arrj with arrj1
23Bubble Sort (2/2)
Showing the first pass
ok
The largest value 90 is at the end of the list.
24Searching
- 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
25Announcement/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!
26Announcement/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
http//www.comp.nus.edu.sg/cs1101x/3_ca/termtests
.html
27This is Week 6
- Next week?
- Recess! (Hooray!)
- The week after next?
- Chapter 6 Object-Oriented Programming (finally!)
- Mid-term test (argh!)
28End of file