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

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

Array. Array Declaration:

Object Oriented Programming. Java-Lecture 6 - Arrays

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

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Testing and Debugging

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

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Lab Assignment Three

Arrays. Eng. Mohammed Abdualal

Last Class. While loops Infinite loops Loop counters Iterations

Computer programming Code exercises [1D Array]

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

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. File Input and Output

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

Arrays. Chapter 7. Walter Savitch Frank M. Carrano

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

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

CS111: PROGRAMMING LANGUAGE II

4. Java language basics: Function. Minhaeng Lee

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

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Chapter 8 Multi-Dimensional Arrays

Programming with Java

Array Basics: Outline

CS S-08 Arrays and Midterm Review 1

COMP 202 Java in one week

AP Computer Science Unit 1. Programs

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

Fundamentals of Programming Data Types & Methods

Introduction to Computer Science Unit 2. Notes

Mr. Monroe s Guide to Mastering Java Syntax

Example: Computing prime numbers

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

Objectives. Order (sort) the elements of an array Search an array for a particular item Define, use multidimensional array

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

CSE 114 Computer Science I

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Java Coding 3. Over & over again!

Arrays. Comp Sci 1570 Introduction to C++ Array basics. arrays. Arrays as parameters to functions. Sorting arrays. Random stuff

The for Loop, Accumulator Variables, Seninel Values, and The Random Class. CS0007: Introduction to Computer Programming

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Chapter 6. Arrays. Java Actually: A Comprehensive Primer in Programming

Introduction to Computer Science Unit 2. Exercises

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

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

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

Arrays and Lists Review CSC 123 Fall 2018 Howard Rosenthal

Object-oriented programming in...

Building Java Programs

Midterm Examination (MTA)

What methods does the String class provide for ignoring case sensitive situations?

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

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

Supplementary Test 1

Anatomy of a Java Program: Comments

1 Short Answer (5 Points Each)

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

Introduction to Computer Science Unit 2. Notes

AP Computer Science A Unit 2. Exercises

2.8. Decision Making: Equality and Relational Operators

Java Errors and Exceptions. Because Murphy s Law never fails

Arrays CHAPTER. 6.1 INTRODUCTION TO ARRAYS 338 Creating and Accessing Arrays 339 The length Instance Variable 342 Initializing Arrays 345

Appendix: Common Errors

Chapter 7: Arrays and the ArrayList Class

Simple Java Reference

Lecture 15. Arrays (and For Loops)

Welcome to the Primitives and Expressions Lab!

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

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

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Chapter 6 SINGLE-DIMENSIONAL ARRAYS

Elementary Programming

CEN 414 Java Programming

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

CS 106 Introduction to Computer Science I

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

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

1. What is the difference between a compiler and an interpreter? Also, discuss Java s method.

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

DM550 Introduction to Programming part 2. Jan Baumbach.

COMP 110/L Lecture 13. Kyle Dewey

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

CS141 Programming Assignment #5

CS 302: Introduction to Programming in Java. Lecture 11 Yinggang Huang. CS302 Summer 2012

CSE 1223: Introduction to Computer Programming in Java Chapter 6 Arrays

ANSWERS. Birkbeck (University of London) Software and Programming 1 In-class Test Feb Student Name Student Number. Answer all questions

CISC-124. Dog.java looks like this. I have added some explanatory comments in the code, and more explanation after the code listing.

Section 2.2 Your First Program in Java: Printing a Line of Text

Tutorial 4. Values and References. Add One A. Add One B. Add One C

Chapter 6 Single-Dimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Arrays. Arrays. Wolfgang Schreiner Research Institute for Symbolic Computation (RISC) Johannes Kepler University, Linz, Austria

Array basics. Readings: 7.1

Array. Prepared By - Rifat Shahriyar

Section 2.2 Your First Program in Java: Printing a Line of Text

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

Programming Language Basics

Transcription:

WIT COMP1000 Arrays

Arrays An array is a list of variables of the same type, that represents a set of related values For example, say you need to keep track of the cost of 1000 items You could declare 1000 double variables: double cost0,cost1,cost2,cost3, Or you could use an array! WIT COMP1000 2

Creating Arrays Creating an array is similar to declaring other variables, with some new Java syntax» The new special symbols we'll be using to denote arrays are brackets [] The general idea is to create a collection of variables all of the same type in one step Here is an example to create an array named cost that holds 1000 double values: double[] cost = new double[1000]; WIT COMP1000 3

WIT COMP1000 4 Creating Arrays double[] cost = new double[1000]; Start with the variable type (double, int, char, String, ) that you want to store in the array followed by [] Then comes the array name (cost, x, vals, ) Next is the Java keyword new followed by the type again and the size of the array in brackets» The number of elements in the array, or the total number of values that the array can hold

Collection of Variables You can think of creating an array as declaring the same number of individual variables Example declaring an array of 8 integers named counts: int[] counts = new int[8]; This is similar to (but not exactly the same as) declaring 8 separate integers: int counts0, counts1, counts2, counts3, counts4, counts5, counts6, counts7; WIT COMP1000 5

Accessing Array Elements To actually use an individual element in the array, you specify the index of the element in brackets Be careful not to confuse the two uses of brackets (creation versus use) Example array of 15 integers named values, and setting the value at index 7 to 10: int[] values = new int[15]; // create an array of 15 ints values[7] = 10; // assign element 7 a value of 10 WIT COMP1000 6

Arrays in Memory Arrays are stored in memory so that all the elements in the array are sequential, in order: int[] counts = new int[8]; counts[3] = 10; address 1000 1004 1008 1012 1016 1020 1024 1028 1032 1036 value 0 0 0 10 0 0 0 0 variable counts[0] counts[1] counts[2] counts[3] counts[4] counts[5] counts[6] counts[7] WIT COMP1000 7

Array Elements and Length Arrays start at index 0 and go through index size 1» Use ARRAY.length to get the size of the array Arrays do NOT start at index 1! Array indices do not have to be hard coded, they can be any expression that evaluates to an integer Example of initializing an array so that all elements have an initial value of 50: double[] temperatures = new double[64]; for (int i = 0; i < temperatures.length; i++) { temperatures[i] = 50; WIT COMP1000 8

Out of Bounds Errors You always have to ensure that your program only uses valid elements/indices for an array You can never access an index of less than 0 You can never access an index greater than or equal to the length of the array If you try to access an element outside of the bounds of the array, Java will give you an ArrayIndexOutOfBoundsException int[] myarray = new int[10]; myarray[0] = 5; // ok myarray[9] = -6; // ok myarray[-1] = 0; // out of bounds error! myarray[10] = 3; // out of bounds error! WIT COMP1000 9

Exercise What is the output of the below code? int[] vals = new int[4]; vals[2] = 3; vals[0] = 2; vals[1] = 1; vals[3] = vals[2]; for (int i = 0; i < vals.length; i++) { System.out.println(vals[i]); WIT COMP1000 10

Answer 2 1 3 3 WIT COMP1000 11

Exercise Write a program that creates an array of 1000 integer values and initializes all of them to 1 WIT COMP1000 12

Answer int[] a = new int[1000]; for (int i = 0; i < a.length; i++) { a[i] = 1; WIT COMP1000 13

Initializing Arrays You can also initialize arrays when you declare them using special syntax with curly braces Example: int[] pages = {513, 343, 279, 409, 651, 222; Above example is equivalent to: int[] pages = new int[6]; pages[0] = 513; pages[1] = 343; pages[2] = 279; pages[3] = 409; pages[4] = 651; pages[5] = 222; WIT COMP1000 14

Array Elements You can use any one element of an array anywhere you can use a variable of the same type» Assigning values» In equations» With input and output statements» As method arguments» WIT COMP1000 15

Examples public class ClassExamples { public static void main(string[] args) { int x; int[] vals = new int[5]; for (int i = 0; i < vals.length; i++) { vals[i] = i*i; x = vals[4] * vals[3] + vals[1]; vals[0] = x - vals[2]; vals[2] = dosomething(vals[1], vals[3]); for (int i = 0; i < vals.length; i++) { System.out.println("vals[" + i + "]=" + vals[i]); public static int dosomething(int a, int b) { return a * 10 + b; WIT COMP1000 16

Arrays as Method Arguments Entire arrays can be passed as methods arguments Array parameters in a method are a bit different than other parameters» Use TYPE[] NAME to indicate the parameter is an array parameter, for example: int[] a Important difference: any changes made to array elements in the method are permanent after the method is finished» In other words, changes made to the array in the method are actually being made to the array in main() (or whoever called the method)» It actually passes a reference into the method (more on this later) WIT COMP1000 17

Example import java.util.scanner; public class ClassExamples { public static void main(string[] args) { Scanner input = new Scanner(System.in); int[] myarray = new int[6]; System.out.print("Enter 6 integers: "); for (int i = 0; i < myarray.length; i++) { myarray[i] = input.nextint(); printarray(myarray); public static void printarray(int[] a) { for (int i = 0; i < a.length; i++) { System.out.println(a[i]); WIT COMP1000 18

import java.util.scanner; Another Example public class ClassExamples { public static void main(string[] args) { Scanner input = new Scanner(System.in); int[] myarray = new int[6]; fillarray(input, myarray); printarray(myarray); public static void fillarray(scanner s, int[] a) { System.out.print("Enter " + a.length + " integers: "); for (int i = 0; i < a.length; i++) { a[i] = s.nextint(); public static void printarray(int[] a) { for (int i = 0; i < a.length; i++) { System.out.println(a[i]); WIT COMP1000 19

Exercise Write a method named addone() that increments every value in an array by one. The array must be passed as an argument to addone(). WIT COMP1000 20

Answer import java.util.scanner; public class ClassExamples { public static void main(string[] args) { Scanner input = new Scanner(System.in); int[] myarray = new int[6]; fillarray(input, myarray); addone(myarray); printarray(myarray); public static void fillarray(scanner s, int[] a) { System.out.print("Enter " + a.length + " integers: "); for (int i = 0; i < a.length; i++) { a[i] = s.nextint(); public static void addone(int[] a) { for (int i = 0; i < a.length; i++) { a[i]++; public static void printarray(int[] a) { for (int i = 0; i < a.length; i++ ) { System.out.println(a[i]); WIT COMP1000 21

Case Study: main Since our first Hello World program we ve seen an array being passed as a parameter to a method» public static void main(string[] args) In this case, the args parameter is an array of arguments being passed to the program from the command line each is a string These are automatically populated for you by the JVM WIT COMP1000 22

Try public class ClassExamples { public static void main(string[] args) { System.out.print(args.length); for (int i = 0; i < args.length; i++) { System.out.println(args[i]); WIT COMP1000 23

Setting Program Arguments in Eclipse Click the Run menu and Run Configurations Find your application on the left list under Java Application Click the Arguments tab on the right Type some values, separated by spaces, into the Program arguments box» Note these will stay until you clear them Click the Run button WIT COMP1000 24

Screenshot

Partially Filled Arrays Arrays do not have to be completely "full" Every element in an array of numeric types is initialized with a value of zero at array creation time» Other types of arrays are initialized to reasonable default values So, you don't have to put a value into every element Depending on your program, you will likely need to keep track of how many elements are actually used in the array WIT COMP1000 26

Example import java.util.scanner; public class ClassExamples { public static void main(string[] args) { Scanner input = new Scanner(System.in); int[] myarray = new int[20]; int usedsize = fillarray(input, myarray); printarray(myarray, usedsize); public static int fillarray(scanner s, int[] a) { System.out.print("Enter up to " + a.length + " integers (stopping with a negative value): "); int i = 0; int temp = s.nextint(); while(temp >= 0 && i < a.length) { a[i] = temp; i++; if (i < a.length) { temp = s.nextint(); return i; public static void printarray(int[] a, int size) { for (int i = 0; i < size; i++ ) { System.out.println(a[i]); WIT COMP1000 27

Searching an Array Sometimes you want to search an array for a particular value or target Look through every element and return the index of one matching element (usually the first) If no element matches the target then usually return -1, since that is never a valid index WIT COMP1000 28

Example import java.util.scanner; public class ClassExamples { public static void main(string[] args) { Scanner input = new Scanner(System.in); int[] values = {4, 11, -3, 0, 46, 11, 9, -77, 3, 11; int target_value, index; System.out.print("Enter a value for which to search: "); target_value = input.nextint(); index = searcharray(values, target_value); if (index == -1) { System.out.println("Target not found!"); else { System.out.println("Target found at index " + index); public static int searcharray(int[] haystack, int needle) { for (int i = 0; i < haystack.length; i++) { if (haystack[i] == needle) { return i; return -1; WIT COMP1000 29

Take Home Points Arrays are useful when you need to keep track of many related values Arrays are almost always used together with loops Array elements can be used anywhere a single variable of the same type can be used Entire arrays can be passed to methods as array arguments» Changes made to the array in the method affect the array in the calling method WIT COMP1000 30