CS 112 Introduction to Programming Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
1 Various Methods of Populating Arrays Randomly generated integers.
Arrays.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
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.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Arrays (Part 1) Computer Science Erwin High School Fall 2014.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
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.
Topic 22 arrays - part 2 Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
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.
Introduction to Java Java Translation Program Structure
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
1 Array basics. Data Structures Sometimes, we have data that have some natural structure to them  A few examples: Texts are sequences of characters Images.
Array - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/19/20151.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading:
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CS 112 Introduction to Programming Loop Patterns: break; Fencepost Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
CS 112 Introduction to Programming Loop Examples; Variable Scoping; Nested Loops; Yang (Richard) Yang Computer Science Department Yale University 208A.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
CS Class 04 Topics  Selection statement – IF  Expressions  More practice writing simple C++ programs Announcements  Read pages for next.
 2005 Pearson Education, Inc. All rights reserved Arrays.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
Topic 21 arrays - part 1 Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from "Should.
Lecture 5 array declaration and instantiation array reference
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Building Java Programs
Dr. Kyung Eun Park Summer 2017
Building Java Programs
Building Java Programs
Arrays Part 1 Topic 19 - Stan Kelly-Bootle
CSC 142 Computer Science II
CSC141 Computer Science I Zhen Jiang Dept. of Computer Science
Building Java Programs Chapter 7
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
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.
Topic 22 arrays - part 2 Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from
Building Java Programs
Building Java Programs
Why did the programmer quit his job?
Building Java Programs
python.reset() Also moving to a more reasonable room (CSE 403)
Building Java Programs
Building Java Programs
Suggested self-checks: Section 7.11 #1-11
Repetition Statements
Building Java Programs
Building Java Programs
File output; Arrays reading: 6.4 – 6.5, 7.1
Building Java Programs
Building Java Programs
Building Java Programs
Arrays.
Presentation transcript:

CS 112 Introduction to Programming Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:

Admin.  Puzzle Day from Friday to Monday 2

Recap: Exceptions  Exception: representing a runtime error  Java allows a method to "throw" an exception, when the method detects a run-time error  Handling exceptions  Declare a throw clause  Use try/catch

Recap: CaesarFile using Loop 4 public static void encode(Scanner scan, int key) { for ( ; scan.hasNextLine(); ) String text = scan.nextLine(); String result = Caesar.encode(text, key); System.out.println( result );} reads ugly public static void encode(Scanner scan, int key) { while ( scan.hasNextLine() ) { String text = scan.nextLine(); String result = Caesar.encode(text, key); System.out.println( result ); }

5 Summary: Flow Control Statements  Loop statements m for m while m do/while  Choosing the loop control structure depends on the specific situation and personal taste while ( condition ) { statement list; } do { statement list; } while ( condition ); for ( initialization ; condition ; increment ) { statement list; }

6 Summary: for loop  for loop is easy to read, since it provides visual aid to recognize the four components  If complex or empty initialization, increment, or condition, a for loop may not read as well as a while or do/while loop m typically used in sequential iteration for ( initialization ; condition ; increment ) { statement list; }

7 Summary: while, do/while loop  The choice between do/while and while depends on the logic of the program: m first check condition or first execute statement while ( condition ) { statement list; } do { statement list; } while ( condition );

Recap: Accessing Elements: Example int[] numbers = new int[10]; numbers[1] = 3; numbers[4] = 99; numbers[6] = 2; System.out.println(numbers[2-1]); if (numbers[4] > 10) { System.out.println(”numbers[4] > 10."); } numbers index value BasicArrays.java

Accessing Elements: Example 9  What does this code segment do? int[] numbers = new int[8]; numbers[0] = 1; numbers[1] = 1; for (int i = 2; i < 8; i++) { numbers[i] = numbers[i-1] + numbers[i-2]; } index value

10 Quick Array Initialization [] = {,, … }; m Examples: int[] numbers = {12, 49, -2, 26, 5, 17, -6}; char[] letterGrades = {'A', 'B', 'C', 'D', 'F'}; String[] wordList = {“cs112“, “computer", “television"}; m The values are delimited by braces and separated by commas m The new operator is not used m The compiler figures out the size by counting the values in the initializer list m Elements in array are initialized with the values in the initializer list  An initializer list can be used to instantiate and initialize an array in one step

11 Exercise: Re-implement Num2Word // map number of 0-4 to English word public static String num2Word(int num) { final String[] map = {“zero”, “one”, “two”, “three”, “four”}; if (num map.length-1) return “Error”; else return map[num]; }

Out-of-bounds (OOB)  Reading or writing any index outside of range will throw an ArrayIndexOutOfBoundsException.  Example (which line(s) will cause OOB): int[] data = new int[10]; System.out.println(data[0]); // okay System.out.println(data[9]); // okay System.out.println(data[-1]); // OOB System.out.println(data[data.length]); // OOB index value

Out-of-bounds (OOB)  Reading or writing any index outside of range will throw an ArrayIndexOutOfBoundsException.  Example (which line(s) will cause OOB): int[] data = new int[10]; System.out.println(data[0]); // okay System.out.println(data[9]); // okay System.out.println(data[-1]); // OOB System.out.println(data[data.length]); // OOB index value

Array length field  Java provides a length field for each array to store the number of elements  It does not use parentheses like a String's.length()  length holds the number of elements, not the largest index  Reference length using the array variable’s name:.length int[] numbers = new int[8]; System.out.println ( numbers.length ); // 8  What expressions refer to the index of: m the last element of any array? m the middle element?

15 Array and Loops Examples

Array as Parameter (Declare) public static ( [] ) {  Example: // Returns the average of the given array of numbers. public static double average(int[] numbers) { int sum = 0; for (int i = 0; i < numbers.length; i++) { sum += numbers[i]; } return (double) sum / numbers.length; }

Array as Parameter (Call) ( );  Example: public class MyProgram { public static void main(String[] args) { // figure out the average TA IQ int[] iq = {126, 109, 149, 167, 125}; double avg = average(iq); System.out.println("Average IQ = " + avg); }...  Notice that you don't write the [] when passing the array.

18 Example: Command-Line Arguments  The signature of the main method indicates that it takes an array of String as a parameter  These values come from command-line arguments that are provided when the interpreter is invoked  For example, the following invocation of the interpreter passes an array of three String objects into main method: > java Calc  The strings “3”, “+”, “5”, are stored at indexes 0-2 of the String array args Exercise: Implement a simple command-line calculator: +|-|*|- See Calc.java

Foundational Programming Concepts 19 objects methods and classes graphics, sound, and image I/O arrays conditionals and loops Mathtext I/O assignment statementsprimitive data types any program you might want to write

Roadmap: Program Flow Control Deterministic for loop (loop counter) cumulative scan loop Early exit loops Fencepost loops

Exercise: Early Exit and boolean method return  Design a method hasAnOddDigit : returns true if any digit of an integer n is odd, e.g.,  hasAnOddDigit( ) returns true  hasAnOddDigit(2448) returns false  Design questions: m How do we loop over each digit from n m If the digit we just saw is odd, can we draw any conclusion? m If the digit is even, can we draw any conclusion? 21 digit = n % 10; n = n / 10; Yes. We found an evidence, return true No, unless we have seen all digits.

Boolean Return Answer public static boolean hasAnOddDigit(int n) { while (n != 0) { int digit = n % 10; if (digit % 2 != 0) { // find an example, // enough to draw conclusion return true; } n = n / 10; } return false; // if we reach here, no // evidence of odd, return false } public static boolean hasAnOddDigit(int n) { while (n != 0) { if (n % 2 != 0) { // find an example, // enough to draw conclusion return true; } n = n / 10; } return false; // if we reach here, no // evidence of odd, return false }

Exercise: Early Exit and boolean method return  Designs method allDigitsOdd : returns true if every digit of an integer is odd.  allDigitsOdd(135319) returns true  allDigitsOdd( ) returns false  Design questions: m If the digit we just saw is odd, can we draw any conclusion? m If the digit is even, can we draw any conclusion? 23 Yes. We found a counter evidence, and can return false No, unless we have seen all digits.

Boolean Return Answer public static boolean allDigitsOdd(int n) { while (n != 0) { if (n % 2 == 0) { // find a counter example, // enough to draw conclusion return false; } n = n / 10; } return true; // if we reach here, no // evidence of counter example, // return true }

Exercise: MatchDB  Design a program to query a match-making database m database (file) format: line 1: number of candidates each line represents a candidate: name age and then a sequence of words (tags) each describing a character m user command list: display each candidate matchAny // print first match any tag matchAll // print first matches all tags 25

Backup Slides 26

Manipulating Array: Array Reversal  Write code that reverses the elements of an array. m For example, if the array initially stores: [11, 42, -5, 27, 0, 89] m Then after your reversal code, it should store: [89, 0, 27, -5, 42, 11] The code should work for an array of any size.

Algorithm Idea  Swap pairs of elements from the edges; work inwards: index value index value index value index value