4CCS1PRP, Programming Practice 2012 Lecture 6: Arrays - Part 1

Similar documents
ARRAYS and ARRAYLISTS

Chapter 6 Arrays and Array Lists

Arrays and Array Lists

Software and Programming I. Classes and Arrays. Roman Kontchakov / Carsten Fuhs. Birkbeck, University of London

Chapter Goals. Contents LOOPS

Introduction to Software Development (ISD) Week 3

Arrays and Basic Algorithms

Collections and Maps

Java Coding 3. Over & over again!

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

Controls Structure for Repetition

Introduction to Software Development (ISD) David Weston and Igor Razgon

CS 302: Introduction to Programming in Java. Lecture 9

Arrays. Eng. Mohammed Abdualal

Introduction to Object-Oriented Programming

Recap: Assignment as an Operator CS 112 Introduction to Programming

CS 101 Spring 2007 Midterm 2 Name: ID:

CSE 114 Computer Science I

CS 112 Introduction to Programming

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

Introduction to Programming Using Java (98-388)

Full file at

Loops. CSE 114, Computer Science 1 Stony Brook University

ECE 122. Engineering Problem Solving with Java

Week 1 Exercises. All cs121 exercise and homework programs must in the default package and use the class names as given.

Introduction to Java Applications

APCS Semester #1 Final Exam Practice Problems

Chapter Goals. T To understand the concept of regression testing. Chapter 6 Arrays and Array Lists. Arrays Array: Sequence of values of the same type

Activity 4: Methods. Content Learning Objectives. Process Skill Goals

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

CS111: PROGRAMMING LANGUAGE II

AP CS Unit 3: Control Structures Notes

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

Darrell Bethea May 25, 2011

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

Java Loop Control. Programming languages provide various control structures that allow for more complicated execution paths.

CP122 CS I. Iteration

CSc 2010 Principles of Computer Science, Fall 2013 Practice Problems for Midterm 3* * 3 17 % 9-20 % (26 / 7) "2"

Mobile App:IT. Methods & Classes

Introduction to Java & Fundamental Data Types

STUDENT LESSON A12 Iterations

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

1. Find the output of following java program. class MainClass { public static void main (String arg[])

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

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Building Java Programs

Lab1 Solution. Lab2 Solution. MathTrick.java. CoinFlip.java

St. Edmund Preparatory High School Brooklyn, NY

PROGRAMMING FUNDAMENTALS

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

CS 101 Spring 2006 Final Exam Name: ID:

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

CS1083 Week 2: Arrays, ArrayList

Java Bytecode (binary file)

CS 231 Data Structures and Algorithms, Fall 2016

Programming with Java

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

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Course Outline. Introduction to java

Pull Lecture Materials and Open PollEv. Poll Everywhere: pollev.com/comp110. Lecture 12. else-if and while loops. Once in a while

CS111: PROGRAMMING LANGUAGE II

Repetition Structures

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

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

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Example: Monte Carlo Simulation 1

Loops and Expression Types

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

Last Time. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Chapter 1 Lab Algorithms, Errors, and Testing

Arrays and Array Lists

Topic 21 arrays - part 1

Over and Over Again GEEN163

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Lecture 14. 'for' loops and Arrays

Computer Science is...

CSE115 / CSE503 Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall Office hours:

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

Flow of Control: Loops. Chapter 4

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

Chapter 5 Control Statements: Part 2 Section 5.2 Essentials of Counter-Controlled Repetition

Lecture 13 & 14. Single Dimensional Arrays. Dr. Martin O Connor CA166

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

BIT Java Programming. Sem 1 Session 2011/12. Chapter 2 JAVA. basic

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:

Software Practice 1 Basic Grammar

COMP 202 Java in one week

Array. Array Declaration:

Administrivia. Last modified: Fri Aug 25 10:59: CS61B: Lecture #2 1

Mr. Monroe s Guide to Mastering Java Syntax

Introduction to Java

Chapter 4 Loops. int x = 0; while ( x <= 3 ) { x++; } System.out.println( x );

FUNDAMENTAL DATA TYPES

Lecture Set 2: Starting Java

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Transcription:

4CCS1PRP, Programming Practice 2012 Lecture 6: Arrays - Part 1 Martin Chapman Java for Everyone by Cay Horstmann Copyright 2009 by John Wiley & Sons. All rights reserved. Slides by Donald W. Smith TechNeTrain.com Modified by Martin Chapman

Arrays Contents The Enhanced for Loop Common Array Algorithms Using Arrays with Methods Two-Dimensional Arrays Array Lists

Chapter Goals To become familiar with using arrays and array lists to collect values To use the enhanced for loop for traversing arrays and array lists To learn about common algorithms for processing arrays and array lists To learn how to use two-dimensional arrays In this chapter, you will learn about arrays, array lists, and common algorithms for processing them.

1. Why do we need arrays?

Sequences of Values A Computer Program often needs to store a list of values and then process them. For example, to find the highest. Say you had this list of values, how many variables would you need? double input1, input2, input3. Impractical for manipulation; unnecessary code replication.

An Example beer Carlsberg, Guinness, Budweiser

An Example beer Carlsberg, Guinness, Budweiser if ( Carlsberg.alcoholPercentage is >= 5 ) then My head hurts otherwise In for work at 9am end if ( Guinness.alcoholPercentage is >= 5 ) then My head hurts otherwise Only a pseudocode example In for work at 9am end if ( Budweiser.alcoholPercentage is >= 5 ) then...

Arrays Are the answer! An array collects sequences of values of the same type.

2. Array Syntax

Declaring an Array Declaring an array is a two step process. 1) double[] data; // declare array variable 2) data = new double[10]; // initialise size You cannot use the array until you tell the compiler the size of the array in step 2.

Declaring an Array (Step 1) Make a named list with the following parts: Type Square Braces Array name semicolon double [ ] data ; You are declaring that There is an array named data The elements inside are of type double You have not (YET) declared how many elements are in inside Other Rules: Arrays can be declared anywhere you can declare a variable Do not use reserved words or already used names

Declaring an Array (Step 2) Reserve memory for all of the elements: Array name Keyword Type Size semicolon data = new double [10] ; You are reserving memory for: The array named data Needs storage for [10] Elements the size of type double You are also setting up the array variable Now the compiler knows how many elements there are data [0] [1] [2] [3] [4] [9] double double double double double double

Common Error 1 Uninitialised Arrays Don t forget to allocate the array contents! The compiler will catch this error double[] data;... data[0] = 29.95; // Error data not initialised double[] data; data = new double[10]; data[0] = 29.95; // No error data 0 1 2 3 4 5 6 7 Error: D:\Java\Unitialised.java:7: variable data might not have been initialized 8 9

One Step Array Declaration Declare and Create at the same time: Type Braces Array name Keyword Type Size semi double [] data = new double [10] ; You are declaring that There is an array named data The elements inside are of type double You are reserving memory for the array Needs storage for [10] Elements the size of type double You are also setting up the array variable

Declaring and Initialising an Array You can declare and set the initial contents of all elements by: Type Braces Array name contents list semi int [ ] primes = 2, 3, 5, 7 ; You are declaring that There is an array named primes The elements inside are of type int Reserve space for four elements No need for new keyword, the compiler counts them for you. Set initial values to 2, 3, 5, and 7 Note the curly braces around the contents list

3. Accessing Arrays

Accessing Array Elements Each element is numbered We call this the index Access an element by: Name of the array Index number data[i] Elements in the array data are accessed by an integer index i, using the notation data[i]. public static void main(string[] args) double data[]; data = new double[10]; data[4] = 35; System.out.println(data[4]);

Array Index Numbers Array index numbers start at 0 The rest are positive integers A 10 element array has indexes 0 through 9 There is NO element 10! The first element is at index 0: public static void main(string[] args) double data[]; data = new double[10]; The last element is at index 9:

Problem: Common Error 2 Array Bounds Errors Accessing a nonexistent element is very common error Array indexing starts at 0 Your program will stop at run time public class OutOfBounds public static void main(string[] args) double data[]; data = new double[10]; data[10] = 100; The is no element 10: java.lang.arrayindexoutofboundsexception: 10 at OutOfBounds.main(OutOfBounds.java:7)

Solution: Array Bounds Checking An array knows how many elements it can hold data.length is the size of the array named data It is an integer value (index of the last element + 1) Use this to range check and prevent bounds errors public static void main(string[] args) int i = 10, value = 34; double data[]; data = new double[10]; if (0 <= i && i < data.length) // value is 10 data[i] = value;

Visiting Array Elements An array knows how many elements it can hold data.length is the size of the array named data It is an integer value (index of the last element + 1) Similarly, use this to visit all the elements in an array. public static void main(string[] args) int[ ] data = 1, 2, 3, 4, 5 ; for ( int i = 0; i < data.length; i++ ) System.out.println( data[ i ] );

Back to Beer... The benefits of using an array: beer array = Carlsberg, Guinness, Budweiser Set variable i = 0; Loop until i == length of beer array if element at i alcoholcontent is > 5 then My head hurts otherwise In for work at 9am A significant decrease in code. end increase i by 1. Next Loop.

To recap...

Array Syntax Review To declare an array, specify the: Array variable name Element Type Length (number of elements)

Summary: Declaring Arrays

4. Array Limitations

Problems? double[] inputs = new double[? ]; for (i = 0; i < inputs.length; i++) inputs[i] = in.nextdouble();

Problems? double[] inputs = new double[? ]; for (i = 0; i < inputs.length; i++) inputs[i] = in.nextdouble(); double[] inputs = new double[100]; while (in.hasnextdouble()) inputs[? ] = in.nextdouble();

Problems? for (int i = 0; i <? ; i++) System.out.println(data[i]);

Partially-Filled Arrays An array cannot change size at run time The programmer may need to guess at the maximum number of elements required It is a good idea to use a constant for the size chosen A partial solution? Use a variable to track how many elements are filled

Partially-Filled Arrays final int LENGTH = 100; double[] data = new double[length]; int currentsize = 0; Scanner in = new Scanner(System.in); while (in.hasnextdouble()) if (currentsize < data.length) data[currentsize] = in.nextdouble(); currentsize++; Use the.length value and currentsize variable to prevent over-filling the array

Walking a Partially Filled Array for (int i = 0; i < currentsize; i++) System.out.println(data[i]); A for loop is a natural choice to walk through an array Use currentsize, not data.length for the last element

A shortcut: The Enhanced for Loop double[] data =...; double sum = 0; for (double element : data) sum = sum + element; Using for loops to walk arrays is very common The enhanced for loop simplifies the process Also called the for each loop Read this code as: For each element in data

A shortcut: The Enhanced for Loop double[] data =...; double sum = 0; for (double element : data) sum = sum + element; As the loop proceeds, it will: Access each element in order (0 to length -1) Copy it to the element variable Execute loop body Not possible to: Change elements Get bounds error

Syntax: The for each loop Use the for each loop when: You need to access every element in the array You do not need to change any elements of the array

Common Array Algorithms Practical array implementations: Filling an Array Sum and Average Values Maximum and Minimum Output Elements with Separators Linear Search Removing an Element Inserting an Element Copying Arrays Reading Input

Common Algorithms 1: 1) Filling an Array Initialise an array to a set of calculated values Example: Fill an array with squares of 0 through 10 int[] squares = new int[11]; for (int i = 0; i < squares.length; i++) squares[i] = i * i;

Common Algorithms 2: 2) Sum and Average Use for each loop, and make sure not to divide by zero double total = 0, average = 0; for (double element : data) total = total + element; if (data.length > 0) average = total / data.length;

Common Algorithms 3: double largest = data[0]; for (int i = 1; i < data.length; i++) if (data[i] > largest) largest = data[i]; Typical for loop to find maximum Maximum and Minimum Set largest to first element Use for or a for each loop Use the same logic for minimum double largest = data[0]; for (double element : data) if (element > largest) largest = element; for each to find maximum double smallest = data[0]; for (double element : data) if (element < smallest) smallest = element; for each to find minimum

Common Algorithms 4: Element Separators Output all elements with separators between them No separator before the first or after the last element for (int i = 0; i < data.length; i++) if (i > 0) System.out.print(" "); System.out.print(data[i]); Handy Array method: Arrays.toString() Useful for debugging! import java.util.*; System.out.println(Arrays.toString(data));

Common Algorithms 5: Linear Search Search for a specific value in an array Start from the beginning (left), stop if/when it is found Uses a boolean found flag to stop loop if found int searchedvalue = 100; int pos = 0; Compound condition to prevent boolean found = false; while (pos < data.length &&!found) bounds error if value not found. if (data[pos] == searchedvalue) found = true; else pos++; if (found) System.out.println( Found at position: + pos); else System.out.println( Not found );

Common Algorithms 6: Removing an element (at a given position) Requires tracking the current size (# of valid elements) But don t leave a hole in the array! Solution depends on if you have to maintain order If not, find the last valid element, copy over position, update size data[pos] = data[currentsize 1]; currentsize--;

Common Algorithms 6: Removing an element (at a given position) Requires tracking the current size (# of valid elements) But don t leave a hole in the array! Solution depends on if you have to maintain order If so, move all of the valid elements after pos up one spot, update size for (int i = pos; i < currentsize - 1; i++) data[i] = data[i + 1]; currentsize--;

Common Algorithms 7: Inserting an Element Solution depends on if you have to maintain order If so, find the right spot for the new element, move all of the valid elements after pos down one spot, insert the new element, and update size If not, just add it to the end and update the size if (currentsize < data.length) for (int i = currentsize; i > pos; i--) data[i] = data[i - 1]; data[pos] = newelement; currentsize++;

Note: Array References Make sure you see the difference between the: Array variable: The named handle to the array Array contents: Memory where the values are stored int[] scores = 10, 9, 7, 4, 5 ; Array variable Array contents Reference An array variable contains a reference to the array contents. The reference is the location of the array contents (in memory). Values

Note: Array Aliases You can make one array reference refer to the same contents of another: int[] scores = 10, 9, 7, 4, 5 ; Int[] values = scores; // Copying the array reference Array contents An array variable specifies the location of an array. Copying the reference yields a second reference to the same array. References

Common Algorithms 8: Copying Arrays Not the same as copying only the reference Only have one actual set of contents!

Common Algorithms 8: Want to copy the contents of one array to another Use the Arrays.copyOf method double[] data = new double[6];... // Fill array double[] prices = data; // Only a reference so far double[] prices = Arrays.copyOf(data, data.length); // copyof creates the new copy, returns a reference

Common Algorithms 8: Growing an array Copy the contents of one array to a larger one Change the reference of the original to the larger one Example: Double the size of an existing array Use the Arrays.copyOf method Use 2 * in the second parameter double[] values = new double[6];... // Fill array double[] newvalues = Arrays.copyOf(values, 2 * values.length); values = newvalues; Arrays.copyOf second parameter is the length of the new array

Increasing the Size of an Array - Step 1 Copy all elements of values to newvalues double[] newvalues = Arrays.copyOf(values, 2 * values.length);

Increasing the Size of an Array - Step 2 Then copy newvalues reference over values reference values = newvalues;

Common Algorithms 9: Reading Input Solution depends on if know how many values to expect If so, make an array of that size and fill it one-by-one double[] inputs = new double[number_of_inputs]; for (i = 0; i < inputs.length; i++) inputs[i] = in.nextdouble();

Common Algorithms 9: Reading Input Solution depends on if know how many values to expect If so, make an array of that size and fill it one-by-one double[] inputs = new double[number_of_inputs]; for (i = 0; i < inputs.length; i++) inputs[i] = in.nextdouble(); If not, make an array large enough for the maximum, and add values to the end until no more are available. double[] inputs = new double[max_inputs]; int currentsize = 0; while (in.hasnextdouble() && currentsize < inputs.length) inputs[currentsize] = in.nextdouble(); currentsize++;

Common Algorithms 9: Reading Input A better solution: double the array when it is full. Able to handle input of arbitrary length double[] inputs = new double[initial_size]; int currentsize = 0; while (in.hasnextdouble()) if (currentsize >= inputs.length) inputs = Arrays.copyOf(inputs, 2 * inputs.length); inputs[currentsize] = in.nextdouble(); currentsize++;

LargestInArray.java (1) Input values and store in next available index of the array

LargestInArray.java (2) Use a for loop and the Find the largest algorithm

Common Error 3 Underestimating the Size of the Data Set The programmer cannot know how someone might want to use a program! Make sure that you write code that will politely reject excess input if you used fixed size limits Sorry, the number of lines of text is higher than expected, and some could not be processed. Please break your input into smaller size segments (1000 lines maximum) and run the program again.

Think you re ahead? Friday 2pm - 4pm, Lab S4.01 Objects, classes, data structures, GUIs... martin.chapman@kcl.ac.uk

Feel like you re behind? Friday 2pm - 4pm, Lab S4.01 Cover all basic concepts. martin.chapman@kcl.ac.uk