CS1101: Programming Methodology Aaron Tan.

Slides:



Advertisements
Similar presentations
Chapter 7: Arrays In this chapter, you will learn about
Advertisements

Garfield AP Computer Science
1 Various Methods of Populating Arrays Randomly generated integers.
CS102--Object Oriented Programming Discussion 2: (programming strategy in java) – Two types of tasks – The use of arrays Copyright © 2008 Xiaoyan Li.
HST 952 Computing for Biomedical Scientists Lecture 9.
CIS 101: Computer Programming and Problem Solving Lecture 7 Usman Roshan Department of Computer Science NJIT.
Wednesday, 12/11/02, Slide #1 CS 106 Intro to Comp. Sci. 1 Wednesday, 12/11/02  QUESTIONS??  Today: CLOSING CEREMONIES!  HW #5 – Back Monday (12/16)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
Simple Sorting Algorithms. 2 Bubble sort Compare each element (except the last one) with its neighbor to the right If they are out of order, swap them.
LAB 10.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic concepts and uses of arrays ❏ To be able to define C.
CHAPTER 7: SORTING & SEARCHING Introduction to Computer Science Using Ruby (c) Ophir Frieder at al 2012.
CS1101: Programming Methodology Aaron Tan.
CS1101: Programming Methodology Aaron Tan.
Java Unit 9: Arrays Declaring and Processing Arrays.
CS1101: Programming Methodology Aaron Tan.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
UNIT 18 Searching and Sorting.
Problem Solving and Algorithms
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Course Web Page Most information about the course (including the syllabus) will be posted on the course wiki:
Chapter 8 Arrays and Strings
Chapter 10 Strings, Searches, Sorts, and Modifications Midterm Review By Ben Razon AP Computer Science Period 3.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
COMP Recursion, Searching, and Selection Yi Hong June 12, 2015.
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
The basics of the array data structure. Storing information Computer programs (and humans) cannot operate without information. Example: The array data.
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.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
CS1101: Programming Methodology Aaron Tan.
Simple Iterative Sorting Sorting as a means to study data structures and algorithms Historical notes Swapping records Swapping pointers to records Description,
CS1101: Programming Methodology Aaron Tan.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
1 2. Program Construction in Java. 2.9 Sorting 3 The need Soritng into categories is relatively easy (if, else if, switch); here we consider sorting.
CS1101: Programming Methodology
DT249-Information Systems Research Practice Programming Revision Lecture 2 Lecturer: Patrick Browne.
CS1101: Programming Methodology Aaron Tan.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
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.
ALGORITHMS.
Homework 8 Due ( MT sections ) ( WTh sections ) at midnight Sun., 10/28 Mon., 10/29 Problems Reading is under week 7, however.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 4 Introduction.
Functions Structured Programming. Topics to be covered Introduction to Functions Defining a function Calling a function Arguments, local variables and.
Simple algorithms on an array - compute sum and min.
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.
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.
CS1020 Data Structures and Algorithms I Lecture Note #6 Vector and ArrayList.
CS 116 Object Oriented Programming II Lecture 4 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 9: Arrays; Revision Session.
CS1010 Programming Methodology
Single Dimensional Arrays
Introduction to Search Algorithms
Simple Sorting Algorithms
Chapter 7 Part 1 Edited by JJ Shepherd
CS1010 Programming Methodology
3.1 Algorithms (and real programming examples).
Building Java Programs
Week 4 Lecture-2 Chapter 6 (Methods).
COMPUTER PROGRAMMING SKILLS
Presentation transcript:

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