Chapter 6 SINGLE-DIMENSIONAL ARRAYS

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

14. Array Basics. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Arrays (Deitel chapter 7)

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

Chapter 7 Single-Dimensional Arrays

array Indexed same type

CS115 Principles of Computer Science

Opening Problem EXAMPLE. 1. Read one hundred numbers, 2. compute their average, and 3. find out how many numbers are above the average.

Chapter 7: Single-Dimensional Arrays. Declaring Array Variables. Creating Arrays. Declaring and Creating in One Step.

Module 7: Arrays (Single Dimensional)

Arrays. Introduction to OOP with Java. Lecture 06: Introduction to OOP with Java - AKF Sep AbuKhleiF - 1

Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world

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

Programming for Engineers Arrays

Announcements. PS 4 is ready, due next Thursday, 9:00pm. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Arrays. Eng. Mohammed Abdualal

Chapter 6 Arrays and Strings Prentice Hall, Inc. All rights reserved.

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

15. Arrays and Methods. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

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

Arrays Introduction. Group of contiguous memory locations. Each memory location has same name Each memory location has same type

Outline. 7.1 Introduction. 7.2 Arrays. 7.2 Arrays

CS1150 Principles of Computer Science Arrays

C How to Program, 7/e by Pearson Education, Inc. All Rights Reserved.

Full file at

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

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

Object Oriented Programming. Java-Lecture 6 - Arrays

High Institute of Computer Science & Information Technology Term : 1 st. El-Shorouk Academy Acad. Year : 2013 / Year : 2 nd

Chapter 9 Introduction to Arrays. Fundamentals of Java

Example: Computing prime numbers

Multiple-Subscripted Arrays

Lecture #8-10 Arrays

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Instructor: Eng.Omar Al-Nahal

C++ PROGRAMMING SKILLS Part 4: Arrays

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

Array. Prepared By - Rifat Shahriyar

Chapter 5 - Methods Prentice Hall, Inc. All rights reserved.

Administration. Objects and Arrays. Objects. Agenda. What is an Object? What is a Class?

Arrays. Lecture 11 CGS 3416 Spring March 6, Lecture 11CGS 3416 Spring 2017 Arrays March 6, / 19

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

Lab Session # 5 Arrays. ALQUDS University Department of Computer Engineering

CS 231 Data Structures and Algorithms, Fall 2016

Chapter 7 Array. Array. C++, How to Program

Arrays. Lecture 11 CGS 3416 Fall October 26, 2015

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

BTE2313. Chapter 2: Introduction to C++ Programming

1 Lexical Considerations

A First Book of ANSI C Fourth Edition. Chapter 8 Arrays

Computational Expression

Introduction to Java & Fundamental Data Types

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

Review of Important Topics in CS1600. Functions Arrays C-strings

Programming with Java

ECE 122. Engineering Problem Solving with Java

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Arrays Data structures Related data items of same type Remain same size once created Fixed-length entries

Java-Array. This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.

EC312 Chapter 4: Arrays and Strings

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

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

TOPICS TO COVER:-- Array declaration and use.

CS313D: ADVANCED PROGRAMMING LANGUAGE

Primitive Types. Four integer types: Two floating-point types: One character type: One boolean type: byte short int (most common) long

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Lexical Considerations

Last Class. While loops Infinite loops Loop counters Iterations

CS111: PROGRAMMING LANGUAGE II

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

Lexical Considerations

EXERCISES SOFTWARE DEVELOPMENT I. 04 Arrays & Methods 2018W

Lecture 14. 'for' loops and Arrays

2. [20] Suppose we start declaring a Rectangle class as follows:

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

Course PJL. Arithmetic Operations

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

C++ Arrays and Vectors

A Quick and Dirty Overview of Java and. Java Programming

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Lecture 15. Arrays (and For Loops)

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

Chapter 7 : Arrays (pp )

Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen)

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

Software Practice 1 Basic Grammar

Lecture 2 Arrays, Searching and Sorting (Arrays, multi-dimensional Arrays)

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

The first applet we shall build will ask the user how many times the die is to be tossed. The request is made by utilizing a JoptionPane input form:

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Objectives. In this chapter, you will:

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

Chapter 2 Basic Elements of C++

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Transcription:

Chapter 6 SINGLE-DIMENSIONAL ARRAYS Lecture notes for computer programming 1 Faculty of Engineering and Information Technology Prepared by: Iyad Albayouk

What is an Array? A single array variable can reference a large collection of data. Arrays have three important properties: arrays represent a group of related data (for example, temperature for the last five days, or stock prices for the last 30 days.) all data within a single array must share the same data type (for example, you can create an array of ints or an array of floats, but you cannot mix and match ints with floats.) The size of an array is fixed once it is created.

What exactly are we talking about?! Let s say you have ten students and you want to save the grades for each of them for use throughout your program (i.e. we need to remember every grade not just loop and count them or average them, etc.) Could do it the hard way: Set up ten variables called studentonegrade, studenttwograde, studentthreegrade, etc. Very difficult to use and manipulate Instead, could use an array to do it the easy way

Using an array variable Create an array variable called studentgrades[10] Declared as follows: int studentgrades[] = new int[10]; This sets up a location in memory for 10 integers which can be referenced using studentgrades[ [ # ] where # is the particular student you want to look at.

Array Naming Considerations The rules for naming variables apply when selecting array variable names Composed of letters, digits, dollar signs and underscore characters Cannot start with a digit Follow all the good programming hints recommended for variable names i.e. just think of it as an ordinary variable when making up the name In addition it is bad style to end an array name with a digit ie. array3[5]

Parts of the array The array has some terminology we haven t seen yet Elements Index Position Number Subscript Zeroth element Keyword new

Elements Refers to the individual items represented by the array. For example, an array of 10 integers is said to have 10 elements an array of 15 floats has 15 elements an array of 5 characters has 5 elements and so on

Index (Position Number or Subscript) Refers to one particular element in the array Also known as position number or, more formally, as a subscript The first element in an array is represented by an index or subscript of 0 (zero). For example, studentgrades[ [ 0 ] This first position is known as the zeroth element The second position is referred to by studentgrades[ [ 1 ]

Figuring out the array positions In Java, an arrays elements start out at index 0 and go up to (the number of elements 1) For example, our array of 10 student grades filled in with grades might look like: Index 0 1 2 3 4 5 6 7 8 9 Value 85 76 99 38 78 98 89 90 82 88

Array positions (cont d) We can access them by specifying the array name followed by square brackets with the index number between them. For example, System.out.println ("The third student s s grade is " + studentgrades[ [ 2 ] ); Would print only the third integer spot in the array (remember 0 is the first, 1 is the second, and 2 is the third element s index / subscript) The output would look like the following: The third student s grade is 99

Array positions (cont d) The index scheme starting at 0 may be initially confusing. This is the cause of many off-by-one errors so study the concept carefully The element in the array s first position is sometimes referred to as the zeroth element. Notice the difference between "position" and "element number"

subscript terminology From this point forward, for this class, all references to array elements will refer to the subscript of the array. In the event that we want to discuss the position of an element in an array, we will refer to it s position. In other words, we will not use i'th element or element i notation unless we are referring to the zeroth element.

Keyword new As we will see, the keyword new is used in Java when you wish to create a new object. In Java, arrays are objects. As with all data members of objects, the elements of the each position in a new array will automatically be initialized to the default value for the array s type.

Some powerful features of arrays Can use expressions as the subscript E.g. if variables a = 1 and b = 2 studentgrades[ [ a + b ] would be the same as writing studentgrades[ [ 3 ] Can use array elements in expressions E.g. int gradetotal = 0 ; gradetotal = studentgrades[ [ 0 ] + studentgrades[ [ 1 ] + studentgrades[ [ 2 ] + etc studentgrades[ [ 9 ] ; Would add up all the array elements and store them in gradetotal.

Powerful features (cont d) Can set array elements equal to other values or expressions. For example, studentgrades[ [ 1 ] = 100 ; This would set the array element with a subscript of 1 to a grade of 100. That is, the second student would have a grade of 100. Java allows us to access an array s length by using the following notation: studentgrades.length would evaluate to 10

So how do we use arrays? Same concepts as other variables apply Must declare the array Must initialize the array (unlike regular variables, Java will automatically initialize arrays with default values) Arrays variables are actually reference variables. Can use arrays in expressions and methods, setting elements values or using their values, similar to the use of ordinary variables

Declaring an array First you can declare an array reference variable (you must specify the type of the elements in the array) : int [] myfirstarray; //declares an array //variable for ints Note: the line above does not allocate memory for the array (it cannot since we have not said the size of the array yet). It only sets aside enough memory to reference the array. Until we create an array, the reference is to null. Next, we create the array and point the reference to it: myfirstarray = new int [10]; To create the array, we need the number of elements in the array so the computer can set aside adequate memory for the array. We can combine the declaration and allocation lines into one line as follows: int [] myfirstarray = new int [10];

Initializing array with a for loop After declaring an array, you can initialize it in the body of your program by using a for loop: int [] myfirstarray = new int [ 5 ]; for (int( i = 0 ; i <= 4 ; i++ ) { myfirstarray[ [ i ] = 1 ; } // end for Note the upper bound is 4, not 5! That is, you loop through 0 to 4 to initialize an array with 5 elements Note: Array elements are initialized with default values. Numeric types get 0, boolean get false and char gets the null character (ascii code 0).

Declaring arrays (cont) You can use a constant to set the size of the array final int NUM_STUDENTS_IN_CLASS = 8 int [] exams = new int [NUM_STUDENTS_IN_CLASS ]; In Java, you do not need to know the size of the array at COMPILE time. Instead you can know the size at RUN time. For example, the following is legal: inputstring = JOptionPane.showInputDialog ("How many students?"); int students = Integer.parseInt (inputstring); int [] myfirstarray = new int [students];

Initializing an Array You can initialize an array when you declare it, as you do with other variables Syntax is slightly different, as you are now initializing more than one element at a time One way at declaration, using initializers: int myfirstarray[ [ ] = { 0, 0, 0, 0, 0 }; Note the braces around the initial zeroes which themselves are separated by commas. Also note that creating arrays in this way eliminates the need for the keyword new.

Accessing elements with for loop Can use a for loop to print the contents of an array int [] myfirstarray = new int [ 5 ]; for (int( i = 0 ; i <= myfirstarray.length 1; i++ ) { System.out.println ("array element " + i + " is equal to " + myfirstarray [i]); } // end for For an array of the char[ ] type, it can be printed using one print statement. For example, the following code displays IYAD : char[ ] name = { I {, Y, A, D }; System.out.println(name);

for-each Loops Outline In general, the syntax for a for-each loop is for (elementtype( element: arrayrefvar) ) { } // Process the element For example, the following code displays all the elements in the array mylist : for(double u: mylist) { System.out out.println(u); } 2003 Prentice Hall, Inc. All rights reserved.

Array Bounds Very Important: Java does not provide array bounds checking at compile time. This means that your program will crash at run time of you try to access memory outside of an array s bounds. For example, suppose you have: int [] myfirstarray = new int [ 10 ]; myfirstarray[100] = 45; 100 is very far outside your defined size (0..9) However, the compiler will not indicate an error.

Outline Example Using Arrays Using histograms do display array data graphically Histogram Plot each numeric value as bar of asterisks (*) 2003 Prentice Hall, Inc. All rights reserved.

1 // Histogram.java 2 // Histogram printing program. 3 import javax.swing.*;.*; 4 5 public class Histogram { 6 Declare array with initializer list 7 public static void main( String args[] ) 8 { 9 int array[] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 }; 10 11 String output = "Element\tValue tvalue\thistogram thistogram"; 12 13 // for each array element, output a bar in histogram 14 for ( int counter = 0; counter < array.length; counter++ ) { 15 output += "\n" + counter + "\t" + array[ counter ] + "\t" t"; 16 17 // print bar of asterisks 18 for ( int stars = 0; stars < array[ counter ]; stars++ ) 19 output += "*"; 20 21 } // end outer for 22 23 JTextArea outputarea = new JTextArea(); 24 outputarea.settext( output ); 25 For each array element, print associated number of asterisks Outline Histogram.java Line 9 Declare array with initializer list Line 19 For each array element, print associated number of asterisks 2003 Prentice Hall, Inc. All rights reserved.

26 JOptionPane.showMessageDialog( null, outputarea, 27 "Histogram Printing Program", JOptionPane.INFORMATION_MESSAGE ); 28 29 System.exit( 0 ); 30 31 } // end main 32 33 } // end class Histogram Outline Histogram.java 2003 Prentice Hall, Inc. All rights reserved.

References and Reference Parameters Outline Two ways to pass arguments to methods Pass-by-value Copy of argument s value is passed to called method In Java, every primitive is pass-by-value Pass-by-reference Caller gives called method direct access to caller s data Called method can manipulate this data Improved performance over pass-by-value In Java, every object is simulated pass-by-reference In Java, arrays are objects Therefore, arrays are passed to methods by reference Technically, we are using pass by value but the value we are passing is a reference to the array. 2003 Prentice Hall, Inc. All rights reserved.

Passing Arrays to Methods Outline To pass array argument to a method Specify array name without brackets Array hourlytemperatures is declared as int [ ] mylist ={1,2,3,4}; The method call printarray( mylist ); Or printarray( ( new int[]{1,2,3,4} ); 2003 Prentice Hall, Inc. All rights reserved.

Passing arrays to methods (cont) In the method header, use similar syntax as that for array declaration: public static void printarray (int array [] ) or public static void ptintarray (int [] array ) For example, the following method displays the elements in an int array: Public static void printarray(int [] array){ for(int i=0 ; i < array.length ; ++i) system.out.println( array[i] ] + ); }

Example for pass by sharing Outline Public class Test{ } } public static void main (String [ ] args){ int x=1; int [ ] y = new int [10]; m( x, y ); System.out.println( x is + x); System.out.println( y[0] y[0] is + y[0] ); public static void m( int number, int [ ] numbers){ } number = 1001; numbers[0] = 5555; X is 1 Y[0] is 5555 2003 Prentice Hall, Inc. All rights reserved.

Outline Example for pass by sharing, cont. The primitive type value in x is passed to number, and the reference value in y is passed to numbers. 2003 Prentice Hall, Inc. All rights reserved.

Returning arrays from methods We have seen examples of methods that modify an array. Since the array is passed by reference, it is modified in the original method as well. Another way to return information in an array is to explicitly return the array. For example, a method with the header: public static int [] makearray () Returns an integer array.

Returning arrays (cont) In order to return an array, the method creates the array first. public static int [] makearray () { int [] myarray = new int [10]; for (int( i; i < myarray.length; i++) Myarray [i] = i; return myarray; } The method above creates a new array called myarray, initializes each element and returns the reference to myarray.

Returning arrays (cont) Outline For example, the following method returns an array that is the reversal of another array. For example, the following statement returns a new array list2 with elements 6,5,4,3,2,1 Int [ ] list1={1,2,3,4,5,6}; Int [ ] list2= reverse(list1); 2003 Prentice Hall, Inc. All rights reserved.

Outline Variable-Length Argument Lists A variable number of arguments of the same type can be passed to a method and treated as an array. You can pass a variable number of arguments of the same type to a method. The parameter in the method is declared as follows: typename... parametername Example: 2003 Prentice Hall, Inc. All rights reserved.

Example of Copying Arrays In this example, you will see that a simple assignment cannot copy arrays in the following program. The program simply creates two arrays and attempts to copy one to the other, using an assignment statement.

Copying Arrays Before the assignment list2 = list1; After the assignment list2 = list1; list1 Contents of list1 list1 Contents of list1 list2 Contents of list2 list2 Garbage Contents of list2

Copying Arrays Using a loop: int[] sourcearray = {2, 3, 1, 5, 10}; int[] targetarray = new int[sourcearray.length]; for (int( i = 0; i < sourcearrays.length; ; i++) targetarray[i] ] = sourcearray[i];

The arraycopy Utility arraycopy(sourcearray, src_pos, targetarray, tar_pos,, length); Example: System.arraycopy(sourceArray,, 0, targetarray, 0, sourcearray.length);

The Arrays Class Outline The java.util.arrays class contains useful methods for common array operations such as sorting and searching. For example, the following code sorts an array of numbers and an array of characters. double[ ] numbers = {6.0,4.4,1.9,2.9,3.4,3.5 }; java.util.arrays.sort(numbers); // Sort the whole array char[ ] chars = { a {, A, 4, F, D, P }; java.util.arrays.sort(chars,1, 3);// Sort part of the array from chars[1] to chars[3-1]. 2003 Prentice Hall, Inc. All rights reserved.

The Arrays Class, cont. Outline For example, the following code searches the keys in an array of integers and an array of characters. int[ [] list = {2, 4, 7, 10, 11, 45, 50, 59, 60, 66, 69, 70, 79}; System.out.println( (1) (1) Index is +java.util util.arrays.binarysearch(list,11 )); System.out.println( (2) (2) Index is +java.util util.arrays.binarysearch(list,12 )); char [ ] chars = { a,{ c, g, x, y, z }; System.out.println( (3) (3) Index is +java.util util.arrays.binarysearch(chars, chars, a )); System.out.println( (3) (3) Index is +java.util util.arrays.binarysearch(chars, chars, t )); The output of the preceding code is 1. Index is 4 2. Index is 6 3. Index is 0 4. Index is 4 2003 Prentice Hall, Inc. All rights reserved.