Array basics. How would you solve this? Arrays. What makes the problem hard? Array auto-initialization. Array declaration. Readings: 7.

Similar documents
Array basics. Readings: 7.1

Building Java Programs

Building Java Programs Chapter 7

Building Java Programs

Building Java Programs

Topic 23 arrays - part 3 (tallying, text processing)

Building Java Programs

Arrays. Weather Problem Array Declaration Accessing Elements Arrays and for Loops Array length field Quick Array Initialization Array Traversals

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Building Java Programs

Topic 21 arrays - part 1

AP Computer Science. Arrays. Copyright 2010 by Pearson Education

arrays - part 1 My methods are really methods of working and thinking; this is why they have crept in everywhere anonymously. Emmy Noether, Ph.D.

Building Java Programs

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Lecture 9: Arrays. Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp. Copyright (c) Pearson All rights reserved.

Building Java Programs

CSE 143 Lecture 1. Arrays (review) slides created by Marty Stepp

Admin. CS 112 Introduction to Programming. Recap: Arrays. Arrays class. Array Return (call) Array Return (declare) q Exam 1 Max: 50 Avg/median: 32

CS 112 Introduction to Programming

CS 112 Introduction to Programming

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

Computer Science is...

Object Oriented Programming. Java-Lecture 6 - Arrays

Arrays in Java Using Arrays

Topic 22 arrays - part 2. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from

Building Java Programs

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

Chapter 4: Control Structures I

H212 Introduction to Software Systems Honors

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Arrays: An array is a data structure that stores a sequence of values of the same type. The data type can be any of Java s primitive types:

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

Chapter 8 Multi-Dimensional Arrays

1. An operation in which an overall value is computed incrementally, often using a loop.

Last Class. While loops Infinite loops Loop counters Iterations

1 Short Answer (10 Points Each)

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Arrays

Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist by Allen B. Downey

Lecture 10: Arrays II

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Q5. What values are stored in the array at the comment in main? Note that the incrementall returns void, but does take an int[] parameter.

Loops. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Last Class. More on loops break continue A bit on arrays

Web-CAT submission URL: CAT.woa/wa/assignments/eclipse

CS 106A, Lecture 16 Arrays

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Review pages for the AP CS Exam

Arrays. Eng. Mohammed Abdualal

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Fundamentals of Programming Data Types & Methods

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

CS 112 Introduction to Programming

CAT.woa/wa/assignments/eclipse

Module 7: Arrays (Single Dimensional)

NoSuchElementException 5. Name of the Exception that occurs when you try to read past the end of the input data in a file.

Chapter 7: Arrays and the ArrayList Class

Building Java Programs

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

Example: Computing prime numbers

Sample Midterm Exam #2

Building Java Programs

Building Java Programs

First Exam Computer Programming 326 Dr. St. John Lehman College City University of New York Thursday, 7 October 2010

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

Building Java Programs

1 Short Answer (10 Points Each)

Chapter 8 Multidimensional Arrays

CSE 142 Sample Final Exam #1 (based on Spring 2005's final; thanks to Stuart Reges)

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Method OverLoading printf method Arrays Declaring and Using Arrays Arrays of Objects Array as Parameters

Final Exam. COMP Summer I June 26, points

CSC 1051 Algorithms and Data Structures I. Final Examination May 12, Name: KEY. Question Value Score

Building Java Programs

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each

Topic 12 more if/else, cumulative algorithms, printf

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

CSE 142, Autumn 2011 Midterm Exam: Friday, November 4, 2011

Choose 3 of the 1 st 4 questions (#'s 1 through 4) to complete. Each question is worth 12 points.

Arrays Chris Piech CS106A, Stanford University

CS115 Principles of Computer Science

CS 1083 Introduction to Programming I for Computer Scientists Final Solutions

(A) 99 ** (B) 100 (C) 101 (D) 100 initial integers plus any additional integers required during program execution

Chapter 2: Basic Elements of Java

Introduction to Java & Fundamental Data Types

Transcription:

How would you solve this? Array basics Readings:. Consider the following program: How many days' temperatures? Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Average temp =. days were above average. What makes the problem hard? Arrays We need each input twice to compute the average via a cumulative sum to count how many were above the average What about putting the s into variables? How many variables would we declare? Need a way to declare many variables at once. array: An object that stores many s of the same type. element: a in an array : an integer indicating the position of a in an array - - element element element Array declaration Array auto-initialization Declaring/initializing an array: <type>[] <name> = new <type>[<length>]; int[] numbers = new int[]; When arrays are initially constructed, every element is automatically initialized to a "zero-equivalent". int: double:. boolean: false object type: null (null means "no object") The length can be any integer expression: int x = * + ; int[] data = new int[x % + ];

Array auto-initialization: Example Assigning array elements An array of doubles... An array of booleans false false.. false false Assigning a to an array element: <array name>[<>] = <>; numbers[] = ; numbers[] = -; - Accessing array elements Don't go out of bounds! Using an array element's in an expression: <array name>[<>] Reading or writing any outside the valid range will throw an ArrayIndexOutOfBoundsException. System.out.println(numbers[]); if (numbers[] < ) { System.out.println("Element is negative."); int[] data = new int[]; System.out.println(data[]); System.out.println(data[-]); System.out.println(data[]); System.out.println(data[]); // okay // exception! // okay // exception! - Example Arrays and for loops int[] numbers = new int[]; numbers[] = ; numbers[] = ; numbers[] = ; int x = numbers[]; numbers[x] = ; numbers[numbers[]] = ; // use numbers[] as! x: numbers: Arrays are very commonly used with for loops to access each element for (int i = ; i < ; i++) { System.out.print(numbers[i] + " "); System.out.println(); // end the line of output

Arrays and for loops Arrays and for loops for (int i = ; i < ; i++) { numbers[i] = * i; for (int i = ; i < ; i++) { numbers[i] = i * i; What s in the array? What s in the array? The length field Example An array's length field stores its number of elements. General syntax: <array name>.length NB: Because it's a field (i.e. not a method), it does not use parentheses like a String's.length()! for (int i = ; i < numbers.length; i++) { System.out.print(numbers[i] + " "); What expression refers to the last element of an array? The middle element? How it all started Solution Solve the following problem: // This program reads several days' temperatures from the user // and computes the average and how many days were above average. import java.util.*; How many days' temperatures? Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Day 's high temp: Average temp =. days were above average. public class Weather { public static void main(string[] args) { Scanner console = new Scanner(System.in); System.out.print("How many days' temperatures? "); int days = console.nextint(); int[] temperatures = new int[days]; // array to store days' temperatures int sum = ; for (int i = ; i < days; i++) { // read/store each day's temperature System.out.print("Day " + (i + ) + "'s high temp: "); temperatures[i] = console.nextint(); sum += temperatures[i]; double average = (double) sum / days; int count = ; for (int i = ; i < days; i++) { if (temperatures[i] > average) { count++; // report results System.out.println("Average temp = " + average); System.out.println(count + " days above average"); // see if each day is above average

A multi-counter problem Arrays for counting / tallying Readings:. Problem: Examine a number and count the number of occurrences of every digit. The number contains: two s, one, three s, one, and one Solution? Declare counter variables one per digit. Eeewww!!!! int counter, counter, counter, counter; int counter, counter, counter, counter; int counter, counter; A multi-counter problem An array of counters Problem: Examine a number and count the number of occurrences of every digit. The number contains: two s, one, three s, one, and one Solution: Declare an array of elements the element at i will store the counter for digit i. int[] counts = new int[]; int num = ; int[] counts = new int[]; while (num > ) { int digit = num % ; counts[digit]++; num = num / ; Histogram: Exercise Histogram: Exercise Given a file of integer exam scores, such as: Write a program that will print a histogram of stars indicating the number of students who earned each unique exam score. : ***** : ************ : *** : * : **** Variations: Make a curve that adds a fixed number of points to each score. (But don't allow a curved score to exceed the max of.) Chart the data with a DrawingPanel.

Histogram: Solution Histogram: Solution // Reads an input file of test scores (integers) and displays a // graphical histogram of the score distribution. import java.awt.*; import java.io.*; import java.util.*; public class Histogram { public static final int CURVE = ; // adjustment to each exam score public static void main(string[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("midterm.txt")); int[] counts = new int[]; // counters of test scores - while (input.hasnextint()) { // read file into counts array int score = input.nextint(); score = Math.min(score + CURVE, ); // curve the exam score counts[score]++; // if score is, then counts[]++ // use a DrawingPanel to draw the histogram DrawingPanel p = new DrawingPanel(counts.length * +, ); Graphics g = p.getgraphics(); g.setcolor(color.black); for (int i = ; i < counts.length; i++) { g.drawline(i * +,, i * +, - * counts[i]); for (int i = ; i < counts.length; i++) { if (counts[i] > ) { System.out.print(i + ": "); for (int j = ; j < counts[i]; j++) { System.out.print("*"); System.out.println(); // print star histogram Why are arrays useful Array initialization statement Arrays store a large amount of data accessible from one variable. Arrays help us group related data into elements. Quick array initialization, general syntax: <type>[] <name> = {<>, <>,, <>; int[] numbers = {,, -,,,, - ; Arrays let us access data in random order. Cassette tape vs. DVD - - Useful when you know in advance what the array's element s will be. Example Printing arrays: Arrays.toString int[] a = {,,,,,, ; for (int i = ; i < a.length; i++) { a[i] += a[i - ]; What s in the array? Arrays.toString accepts an array as a parameter and returns the String representation, which you can then print. int[] a = {,,,,,, ; for (int i = ; i < a.length; i++) { a[i] += a[i - ]; System.out.println("a is " + Arrays.toString(a)); a is [,,,,,, ]

Array traversal Traversal algorithms Readings:. traversal: An examination of each element of an array. Traversal algorithms often takes the following form: for (int i = ; i < <array>.length; i++) { do something with <array>[i]; Examples: printing out the elements searching for a specific rearranging the elements computing a based on the elements Printing array elements Searching an array int[] list = {,,, ; for (int i = ; i < list.length; i++) { System.out.println(i + ": " + list[i]); : : : : int[] list = {,,,,,,,,, ; int largesteven = ; for (int i = ; i < list.length; i++) { if (list[i] % == && list[i] > largesteven) { largesteven = list[i]; System.out.println("Largest even: " + largesteven); Largest even: What assumptions does this code make? String traversal String traversal: Example Strings are represented internally as arrays of chars. 'l' 'e' 't' 't' 'e' 'r' We can write algorithms to traverse strings to compute information. What useful information might the following string have? "BDRBRRBDRRBDMBDBRRRBRBRBBDBDDRDDRRDBDBBD" 's' // string stores voters' votes // (R)EPUBLICAN, (D)EMOCRAT, (B)ENSON, (M)ARTY String votes = "BDRBRRBDRRBDMBDBRRRBRBRBBDBDDRDDRRDBDBBD"; int[] counts = new int[]; // R ->, D ->, B ->, M -> for (int i = ; i < votes.length(); i++) { char c = votes.charat(i); if (c == 'R') { counts[]++; else if (c == 'D') { counts[]++; else if (c == 'B') { counts[]++; else { // c == 'M' counts[]++; System.out.println(Arrays.toString(counts)); [,,, ]

Example data: Section attendance Data transformations Consider the following dataset which represents attendance for three sections of five students: week week week week week week week week week Sometimes we will use data in one form to compute new data in another form. Often each transformation is stored into its own array. Transformations require a mapping between the original data and array indices. student student student student student Typical mappings Exercise: Section attendance Tally If the input is the integer i, do something with array i. Based on the position in the data Store the i th we read into i. Explicit mappings Count occurrences of 'R' into and occurrences of 'D' into. Write a program that reads the preceding section data file and produces output such as the following: Section #: Sections attended: [,,,, ] Student scores: [,,,, ] Student grades: [.,.,.,.,.] Section #: Sections attended: [,,,, ] Student scores: [,,,, ] Student grades: [.,.,.,.,.] Section #: Sections attended: [,,,, ] Student scores: [,,,, ] Student grades: [.,.,.,.,.] Solution: Section attendance Solution: Section attendance // This program reads a file representing which students attended // which discussion sections and produces output of the students' // section attendance and scores. import java.io.*; import java.util.*; public class Sections { public static void main(string[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("sections.txt")); int section = ; // used to count sections while (input.hasnextline()) { String line = input.nextline(); processsection(section, line); section++; // one section's data public static void processsection(int sectionnum, String line) { System.out.println("Section #" + sectionnum + ":"); int[] attended = new int[]; // count sections attended for (int i = ; i < line.length(); i++) { char c = line.charat(i); if (c == '') { // student attended section attended[i % ]++; System.out.println("Sections attended: " + Arrays.toString(attended));

Solution: Section attendance // compute section score out of points int[] scores = new int[]; for (int i = ; i < scores.length; i++) { scores[i] = Math.min( * attended[i], ); System.out.println("Student scores: " + Arrays.toString(scores)); Arrays and methods // compute section grade out of % double[] grades = new double[]; for (int i = ; i < scores.length; i++) { grades[i] =. * scores[i] / ; System.out.println("Student grades: " + Arrays.toString(grades)); System.out.println(); Readings:. Arrays as parameters Arrays as parameters Declaration, syntax: public static <type> <name>(<type>[] <name>) { public static double average(int[] numbers) { Method call, syntax: <method name>(<array name>); int[] scores = {,,,, ; double avg = average(scores); public static void main(string[] args) { int[] iq = {,, ; System.out.println("Max = " + max(iq)); public static int max(int[] array) { int largest = array[]; for (int i = ; i < array.length; i++) { if (array[i] > largest) { largest = array[i]; return largest; Max = Arrays as parameters Arrays as parameters Unlike primitive types, when arrays are passed as parameters, changes made to the array elements in the called method will be visible in the calling method. public static void main(string[] args) { int[] iq = {,, ; System.out.println(Arrays.toString(iq)); doubleall(iq); System.out.println(Arrays.toString(iq)); public static void doubleall(int[] array) { for (int i = ; i < array.length; i++) { array[i] *= ; [,, ] [,, ] public static void main(string[] args) { int[] iq = {,, ; System.out.println(Arrays.toString(iq)); doubleall(iq); System.out.println(Arrays.toString(iq)); public static void doubleall(int[] array) { for (int i = ; i < array.length; i++) { array[i] *= ; [,, ] [,, ] array: iq:

Useful result: Output parameter Output parameter output parameter: An object passed as a parameter that has its contents altered by the method. We can pass an array to a method and the method can change its contents in useful ways. After calling Arrays.sort(<array>), the array passed in will be in sorted order. int[] nums = {, -,,,, ; System.out.println(Arrays.toString(nums)); Arrays.sort(nums); System.out.println(Arrays.toString(nums)); [, -,,,, ] [-,,,,, ] Arrays as return s Arrays as return s Declaration, syntax: public static <type>[] <name>(<parameters>) { public static int[] readallnumbers(scanner input) { Method call, syntax: <type>[] <name> = <method name>(<parameters>); Scanner filescan = new Scanner(new File("nums.txt")); int[] numbers = readallnumbers(filescan); public static int[] countdigits(int n) { int[] counts = new int[]; while (n > ) { int digit = n % ; n = n / ; counts[digit]++; return counts; public static void main(string[] args) { int[] tally = countdigits(); System.out.println(Arrays.toString(tally)); [,,,,,,,,, ] Exercises Solutions Write a method named average that accepts an array of integers and returns the average of the s in the array. Write a method named contains that accepts an array of integers and a target integer and returns whether the array contains the target. Write a method named roundall that accepts an array of doubles and modifies each element of the array so that it is rounded to the nearest whole number. public static double average(int[] numbers) { int sum = ; for (int i = ; i < numbers.length; i++) { sum += numbers[i]; return (double) sum / numbers.length; public static boolean contains(int[] s, int target) { for (int i = ; i < s.length; i++) { if (s[i] == target) { return true; return false; public static void roundall(double[] array) { for (int i = ; i < array.length; i++) { array[i] = Math.round(array[i]);

Exercise Solution Modify our previous Sections program to use methods for structure. Pass arrays as parameters and return. Section #: Sections attended: [,,,, ] Student scores: [,,,, ] Student grades: [.,.,.,.,.] Section #: Sections attended: [,,,, ] Student scores: [,,,, ] Student grades: [.,.,.,.,.] Section #: Sections attended: [,,,, ] Student scores: [,,,, ] Student grades: [.,.,.,.,.] // This program reads a file representing which students attended // which discussion sections and produces output of the students' // section attendance and scores. // This version uses methods for structure. import java.io.*; import java.util.*; public class Sections { public static void main(string[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("sections.txt")); while (input.hasnextline()) { // process one section String line = input.nextline(); int[] attended = countattended(line); int[] points = computepoints(attended); double[] grades = computegrades(points); results(attended, points, grades); Solution Solution // Counts the sections attended by each student for one section. public static int[] countattended(string line) { int[] attended = new int[]; for (int i = ; i < line.length(); i++) { char c = line.charat(i); // c == '' or c == '' if (c == '') { // student attended their section attended[i % ]++; return attended; // Computes the points earned for each student for one section. public static int[] computepoints(int[] attended) { int[] points = new int[]; for (int i = ; i < attended.length; i++) { points[i] = Math.min(, * attended[i]); return points; // Computes the percentage for each student for one section. public static double[] computegrades(int[] points) { double[] grades = new double[]; for (int i = ; i < points.length; i++) { grades[i] =. * points[i] /.; return grades; // Produces all output about one section. public static void results(int[] attended, int[] points, double[] grades) { System.out.println("Sections attended: " + Arrays.toString(attended)); System.out.println("Sections scores: " + Arrays.toString(points)); System.out.println("Sections grades: " + Arrays.toString(grades)); System.out.println();