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

Similar documents
Building Java Programs

Topic 21 arrays - part 1

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.

AP Computer Science. Arrays. Copyright 2010 by Pearson Education

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

Building Java Programs Chapter 7

Array basics. Readings: 7.1

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

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

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

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

CS 112 Introduction to Programming

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

CSc 110, Autumn 2016 Lecture 15: lists. Adapted from slides by Marty Stepp and Stuart Reges

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

! 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

Building Java Programs

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

CS 106A, Lecture 16 Arrays

Building Java Programs

Computer Science is...

Chapter 4: Control Structures I

Object Oriented Programming. Java-Lecture 6 - Arrays

Arrays in Java Using Arrays

Arrays. Eng. Mohammed Abdualal

Last Class. While loops Infinite loops Loop counters Iterations

Arrays Chris Piech CS106A, Stanford University

Computer programming Code exercises [1D Array]

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Topic 11 Scanner object, conditional execution

Topic 12 more if/else, cumulative algorithms, printf

Example: Computing prime numbers

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:

Building Java Programs

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

Lab Assignment Three

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

Chapter 7: Arrays and the ArrayList Class

Midterm Examination (MTA)

Building Java Programs

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Searching and Sorting (Savitch, Chapter 7.4)

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

What is an algorithm?

Computação I. Exercises. Leonardo Vanneschi NOVA IMS, Universidade Nova de Lisboa. Leonardo Vanneschi Computação I NOVA IMS

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Building Java Programs

AP Computer Science. Return values, Math, and double. Copyright 2010 by Pearson Education

assertion: A statement that is either true or false.

Building Java Programs

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Lecture 10: Arrays II

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

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Lecture 17. For Array Class Shenanigans

Building Java Programs

Topic 11 Scanner object, conditional execution

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

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

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

CS 1063 Introduction to Computer Programming Midterm Exam 2 Section 1 Sample Exam

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

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

Building Java Programs

Chapter 2: Basic Elements of Java

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

Array. Prepared By - Rifat Shahriyar

Conditional Execution

Advanced if/else & Cumulative Sum

1. What does the following code fragment write to the monitor?

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

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

Building Java Programs

Lecture 17. Instructor: Craig Duckett. Passing & Returning Arrays

CIS November 14, 2017

CIS 1068 Netflix Challenge New assignment posted soon Lab grades November 14, 2017

CS 112 Introduction to Programming

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Loops. CSE 114, Computer Science 1 Stony Brook University

Passing Array to Methods

Tutorial 11. Exercise 1: CSC111 Computer Programming I. A. Write a code snippet to define the following arrays:

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Arrays Chris Piech CS106A, Stanford University

Garfield AP CS. User Input, If/Else. Most slides from Building Java Programs. Thanks, Stuart Regesand Marty Stepp!

Full file at

Topic 12 more if/else, cumulative algorithms, printf

Spring 2010 Java Programming

Java Coding 3. Over & over again!

Data dependent execution order data dependent control flow

Chapter 2. Elementary Programming

Building Java Programs

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

Fundamentals of Programming Data Types & Methods

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

St. Edmund Preparatory High School Brooklyn, NY

AP Programming - Chapter 6 Lecture

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

1 Short Answer (10 Points Each)

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Transcription:

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

Can we solve this problem? Consider the following program (input underlined): How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp: 48 Day 5's high temp: 37 Day 6's high temp: 46 Day 7's high temp: 53 Average temp = 44.6 4 days were above average. 2

Why the problem is hard We need each input value twice: to compute the average (a cumulative sum) to count how many were above average We could read each value into a variable... but we: don't know how many days are needed until the program runs don't know how many variables to declare We need a way to declare many variables in one step. Luckily, Java has a built-in structure, the array, that makes this problem very easy to solve. 3

Arrays array: object that stores many values of the same type. element: One value in an array. index: A 0-based integer to access an element from an array. index value 0 1 2 3 4 5 6 7 8 9 12 49-2 26 5 17-6 84 72 3 element 0 element 4 element 9 4

Array declaration type[] name = new type[length]; Example: int[] numbers = new int[10]; index value 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 5

Array declaration, cont. The length can be any integer expression. int x = 2 * 3 + 1; int[] data = new int[x % 5 + 2]; Each element initially gets a "zero-equivalent" value. Type int 0 Default value double 0.0 boolean String or other object false null (means, "no object") 6

Accessing elements name[index] name[index] = value; // access // modify Example: numbers[0] = 27; numbers[3] = -6; System.out.println(numbers[0]); if (numbers[3] < 0) { System.out.println("Element 3 is negative."); index 0 1 2 3 4 5 6 7 8 9 value 27 0 0 0-6 0 0 0 0 0 0 0 7

Arrays of other types double[] results = new double[5]; results[2] = 3.4; results[4] = -0.5; index value 0 1 2 3 4 0.0 0.0 3.4 0.0-0.5 boolean[] tests = new boolean[6]; tests[3] = true; index value 0 1 2 3 4 5 false false false true false false 10

Out-of-bounds Legal indexes: between 0 and the array's length - 1. Reading or writing any index outside this range will throw an ArrayIndexOutOfBoundsException. Example: int[] data = new int[10]; System.out.println(data[0]); System.out.println(data[9]); System.out.println(data[-1]); System.out.println(data[10]); // okay // okay // exception // exception index value 0 1 2 3 4 5 6 7 8 9 0 0 0 0 0 0 0 0 0 0 9

Ways of Accessing Arrays Sequential Access: accessing and/or manipulating elements of array in a sequential manner from first element to last element for loops Random Access: accessing and/or manipulating elements of array in any order whatsoever with quick access to each element element by index 10

Accessing array elements randomly example int[] numbers = new int[8]; numbers[1] = 3; numbers[4] = 99; numbers[6] = 2; int x = numbers[1]; numbers[x] = 42; numbers[numbers[6]] = 11; // use numbers[6] as index x index 0 1 2 3 4 5 6 7 numbers value 11

Accessing array elements randomly example solution int[] numbers = new int[8]; numbers[1] = 3; numbers[4] = 99; numbers[6] = 2; int x = numbers[1]; numbers[x] = 42; numbers[numbers[6]] = 11; // use numbers[6] as index x 3 numbers index value 0 1 2 3 4 5 6 7 0 3 11 42 99 0 2 0 12

Accessing array elements randomly another problem int[] data = new int[8]; data[7] = 3; data[4] = 1; int x = data[2]; data[2] = 31; data[x] = 4; data[data[0]] = 6; x index 0 1 2 3 4 5 6 7 data value 13

Arrays and for loops (Sequential Access) It is common to use for loops to access array elements. for (int i = 0; i < 8; i++) { System.out.print(numbers[i] + " "); System.out.println(); // output: 0 3 11 42 99 0 2 0 Sometimes we assign each element a value in a loop. for (int i = 0; i < 8; i++) { numbers[i] = 2 * i; index 0 1 2 value 3 4 5 6 7 0 2 4 6 8 10 12 14 14

The length field An array's length field stores its number of elements. name.length for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); // output: 0 2 4 6 8 10 12 14 It does not use parentheses like a String's.length(). What expressions refer to: The last element of any array? The middle element? The first element? 15

The length field (cont) Last element: numbers[numbers.length 1]; Middle element: numbers[numbers.length / 2]; Middle element: numbers[(numbers.length - 1) / 2]; First element: numbers[0]; 16

Initializing Arrays User Input Because arrays are indexed, using a loop to initialize arrays is really efficient Prompt the user for the size of the array and then create an integer array of that size and fill with values that are prompted from the user. Scanner console = new Scanner(System.in); System.out.print("How many numbers? "); int size = console.nextint(); int[] array = new int[size]; for (int i = 0; i < array.length; i++) { System.out.print("Integer: "); while(!console.hasnextint()){ console.next(); System.out.println("Not an integer"); System.out.print("Integer: "); array[i] = console.nextint(); 17

Initializing Arrays Random Create and fill a 100 element integer array with random values between 0 and 99, inclusive. public static final int ARRAY_SIZE = 100; public static final int VALUE_RANGE = 100; Random r = new Random(); int[] a = new int[array_size]; for (int i = 0; i < a.length; i++) { a[i] = r.nextint(value_range); 20

Quick array initialization You can also create an array and give it initial values for each element using a shortcut: type[] name = {value, value, value; Example: int[] numbers = {12, 49, -2, 26, 5, 17, -6; index value 0 1 2 3 4 5 6 12 49-2 26 5 17-6 Useful when you know what the array's elements will be The compiler figures out the size by counting the values 19

"Array mystery" problem What element values are stored in the following array? int[] a = {1, 7, 5, 6, 4, 14, 11; for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { a[i + 1] = a[i + 1] * 2; index 0 1 2 3 4 5 6 value 20

"Array mystery" solution What element values are stored in the following array? int[] a = {1, 7, 5, 6, 4, 14, 11; for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i + 1]) { a[i + 1] = a[i + 1] * 2; index value 0 1 2 3 4 5 6 1 7 10 12 8 14 22 21

Array traversals traversal: An examination of each element of an array. for (int i = 0; i < array.length; i++) { do something with array[i]; Examples: printing the elements searching for a specific value rearranging the elements computing the sum, product, etc. 22

Back to the Weather question Use an array to solve the weather problem: How many days' temperatures? 7 Day 1's high temp: 45 Day 2's high temp: 44 Day 3's high temp: 39 Day 4's high temp: 48 Day 5's high temp: 37 Day 6's high temp: 46 Day 7's high temp: 53 Average temp = 44.6 4 days were above average. 23

Weather answer // Reads temperatures from the user, computes average and # days import java.util.*; 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[] temps = new int[days]; int sum = 0; // array to store days' temperatures for (int i = 0; i < days; i++) { System.out.print("Day " + (i + 1) + "'s high temp: temps[i] = console.nextint(); sum += temps[i]; double average = (double) sum / days; // read/store each day's temperature "); int count = 0; for (int i = 0; i < days; i++) { if (temps[i] > average) { count++; // see if each day is above average // report results System.out.printf("Average System.out.println(count + temp = " days %.1f\n", average); above average"); 26

Lab Exercise Go to the moodle page and work on the ArrayCalculations.java assignment: Write a class called ArrayCalculations that does the following: Declares an integer array named data with the elements 7, -1, 13, 24, and 6. Use only one statement to initialize the array. Calculates and prints the maximum value in the array. Calculates and prints the minimum value in the array. Calculates and prints the sum of all the elements in the array. Calculates and prints the average (a double) of all the elements in the array. System.out.println("\nThe maximum value in the array is: " + maximum); System.out.println("The minimum value in the array is: " + minimum); System.out.println("The sum of the values in the array is: " + sum); System.out.println("The average of the values in the array is: " + average); 27