Cs1101 programming methodology http www comp nus edu sg cs1101x
This presentation is the property of its rightful owner.
Sponsored Links
1 / 28

CS1101: Programming Methodology comp.nus.sg/~cs1101x/ PowerPoint PPT Presentation


  • 70 Views
  • Uploaded on
  • Presentation posted in: General

CS1101: Programming Methodology http://www.comp.nus.edu.sg/~cs1101x/. Aaron Tan. 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

Download Presentation

CS1101: Programming Methodology comp.nus.sg/~cs1101x/

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Cs1101 programming methodology http www comp nus edu sg cs1101x

CS1101: Programming Methodologyhttp://www.comp.nus.edu.sg/~cs1101x/

Aaron Tan


This is week 6

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.


Arrays

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!


Array declaration syntax

Array Declaration Syntax

  • Array declaration syntax:

    <element-type>[] <array-variable>;

    Example: double[] values;

  • Alternative syntax:

    <element-type><array-variable>[];

    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.


Classic array problems

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.


Loading an array

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 15-16 of Chapter 10

We will learn how to read data from a file some other time.


Exercise 1 summing an array

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: 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.


Exercise 2 finding maximum value

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: 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


Common mistake index out of range

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]);

}


Modular programming 1 5

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.)


Modular programming 2 5

Modular Programming (2/5)

Download CheckNRIC.java program which we did before. Here’s the partial code:

These variables are used in the computation of the check 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);

}


Modular programming 3 5

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);

}

Pass number into the method generateCheckCode().

Delegate the job to the method generateCheckCode().

What are you expecting generateCheckCode() to return? A character.


Modular programming 4 5

Modular Programming (4/5)

How does generateCheckCode() method look like?

The method returns a character.

public static char generateCheckCode(int num) {

// Extract digits

int digit7 = num%10; 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.


Modular programming 5 5

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.


Exercise 3 coin change

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?


Method main 1 2

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


Method main 2 2

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


Sorting and searching

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.


Sorting

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.


Selection sort 1 2

Selection Sort (1/2)

min

first

0

0

1

1

2

2

3

3

4

4

5

5

6

6

7

7

8

8

exchange

23

5

17

17

23

5

90

90

12

12

44

44

38

38

84

84

77

77

unsorted

sorted

  • 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.


Selection sort 2 2

Selection Sort (2/2)

Pass #

1

sorted

0

1

2

3

4

5

6

7

8

5

5

5

5

5

12

12

12

12

17

23

17

23

17

17

23

23

90

90

90

17

38

23

38

12

44

44

44

44

44

38

77

38

77

38

84

84

84

84

84

77

77

77

90

90

Result AFTER one pass is completed.

2

3

7

8


Bubble sort 1 2

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?


Bubble sort 2 2

Bubble Sort (2/2)

17

23

23

17

5

5

90

90

12

12

44

44

38

38

84

84

77

77

exchange

exchange

0

1

2

3

4

5

6

7

8

exchange

exchange

17

17

17

17

17

17

5

5

5

5

5

5

23

23

23

23

23

23

12

12

12

12

12

90

44

44

90

44

44

12

44

90

38

38

44

38

84

38

84

38

38

90

84

90

84

84

84

77

77

77

77

90

77

77

exchange

exchange

exchange

Showing the first pass…

ok

The largest value 90 is at the end of the list.


Searching

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


Announcement reminder 1 2

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!


Announcement reminder 2 2

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:http://www.comp.nus.edu.sg/~cs1101x/3_ca/termtests.html


This is week 61

This is Week 6

  • Next week?

    • Recess! (Hooray!)

  • The week after next?

    • Chapter 6 Object-Oriented Programming (finally!)

    • Mid-term test (argh!)


End of file

End of file


  • Login