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

Similar documents
More on control structures

Program Control Flow

Program Control Flow

Object Communication

Chapter 8 Multi-Dimensional Arrays

Object Oriented Programming. Java-Lecture 6 - Arrays

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

Chapter 7 Multidimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

More on Exception Handling

Arrays. Eng. Mohammed Abdualal

Chapter 10. Exception Handling. Java Actually: A Comprehensive Primer in Programming

More on Exception Handling

Spring 2010 Java Programming

Basic Programming Elements

Introduction. Data in a table or a matrix can be represented using a two-dimensional array. For example:

Sorting and searching arrays

Chapter 7 Multidimensional Arrays

Array. Array Declaration:

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

Fundamentals of Programming Data Types & Methods

Implementing Dynamic Data Structures

Multidimensional Arrays. CSE 114, Computer Science 1 Stony Brook University

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

Programming with Java

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

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

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

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

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

CS111: PROGRAMMING LANGUAGE II

Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

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

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

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.

! 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

CS1150 Principles of Computer Science Arrays

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

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

Elementary Programming

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

Java Coding 3. Over & over again!

University of Cape Town ~ Department of Computer Science. Computer Science 1015F ~ 2007

Last Class. While loops Infinite loops Loop counters Iterations

Computer Science is...

COMP 110 Programming Exercise: Simulation of the Game of Craps

Polymorphism and Interfaces

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

Chapter 9 Introduction to Arrays. Fundamentals of Java

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

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

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

H212 Introduction to Software Systems Honors

Instructor: Eng.Omar Al-Nahal

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

array Indexed same type

Arrays. Lecture 11 CGS 3416 Fall October 26, 2015

Object-Based Programming. Programming with Objects

Lecture 15. Arrays (and For Loops)

Chapter 1. Getting started. Java Actually: A Comprehensive Primer in Programming

CS115 Principles of Computer Science

Loops. CSE 114, Computer Science 1 Stony Brook University

Lecture Set 4: More About Methods and More About Operators

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

H212 Introduction to Software Systems Honors

Anatomy of a Java Program: Comments

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

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

CS313D: ADVANCED PROGRAMMING LANGUAGE

Lecture #8-10 Arrays

Array. Prepared By - Rifat Shahriyar

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

CS111: PROGRAMMING LANGUAGE II

Bjarne Stroustrup. creator of C++

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

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Lecture Set 4: More About Methods and More About Operators

4. Java language basics: Function. Minhaeng Lee

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

CSE 114 Computer Science I

Over and Over Again GEEN163

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

Data dependent execution order data dependent control flow

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

CS 231 Data Structures and Algorithms Fall Arrays Lecture 07 - September 19, Prof. Zadia Codabux

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

Give one example where you might wish to use a three dimensional array

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Full file at

Computational Expression

Java Classes: Math, Integer A C S L E C T U R E 8

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 26, 2017

Pace University. Fundamental Concepts of CS121 1

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

Top-Down Program Development

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

CompSci 125 Lecture 11

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

Transcription:

Lecture slides for: Chapter 6 Arrays Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 28. ISBN: 978-1-84448-933-2 http://www.ii.uib.no/~khalid/jac/ Permission is hereby granted to use these lecture slides in conjunction with the book. Modified: 14/11/8 Java Actually 6: Arrays 6-1/2

Overview Using arrays to organize a collection of values. Declaring array references, creating arrays and using arrays. Initializing an array. Iterating over an array. Multidimensional arrays. Common operations on arrays. Generating pseudo-random numbers Java Actually 6: Arrays 6-2/2

Arrays Arrays can be used to create a collection of data values. An array is a collection with a finite number of elements. Elements in an array can be one of the following: either values of a particular primitive data type, or references to objects. All elements in an array have the same element type. An array has a length which corresponds to the number of elements in it, and cannot be changed after the array is created. In Java arrays are objects. Java provides language construction for declaration, creation, initialization and use of arrays. Java Actually 6: Arrays 6-3/2

Declaration: <elementtype> <arrayname> []; Alternative declaration: <elementtype>[] <arrayname>; Arrays (cont.) <elementtype> can be a primitive datatype or a reference type (for example, a class). Declaration alone creates a reference for the array. int[] a; creates a reference to an array of int: a ref int[] Java Actually 6: Arrays 6-4/2

Arrays (cont.) Creation: the array itself is created using the new operator. can combine the declaration with the creation: <elementtype>[] <arrayname> = new <elementtype>[<numofelements>]; double[] d = new double[5]; // creates an array object with 5 // elements of type double. can create an array and assign its reference value to a reference that is already declared: int[] a; a = new int[8]; // creates av array object with 8 // elements of type int Elements are always initialized to the default value for elementtype when the array is created. Each array has a field, length, that indicates the number of elements in the array. Value of a.length is equal to the number of elements array a can hold, i.e 8. Java Actually 6: Arrays 6-5/2

Arrays (cont.) Use: <arrayname> [<index>] index is an integer expression that satisfies the following relation: index < numofelements and (numofelements-1) are lower and upper limits for index, respectively. The value of the index is checked automatically during execution. If index numofelements or index <, an ArrayIndexOutOfBoundsException is thrown at runtime. Notation above can interpreted as variable: a[2] indicates the 3rd element in the array a. a[2] = 5; a[2] = 3 * a[2]; // a[2] is assigned the value 15. Java Actually 6: Arrays 6-6/2

Example of an array // Declaration and creation int[] drawers = new int[1]; // indexed variable: drawers[], drawers[1],..., // drawers[9]; // Each indexed variable corresponds to a drawer. // int drawers, drawers1, drawers2, drawers3, drawers4, // drawers5, drawers6, drawers7, drawers8, drawers9; // Explicit initialization drawers[] = 29; indexed variable 1 1 length drawers // use drawers[2] = drawers[]+5; array navn... for (int i = ; i < drawers.length; i++) drawers[i] = 1; // drawers[1] does not exist! index 9 2... 34 Java Actually 6: Arrays 6-7/2

Arrays: Graphical Notation Declaration, creation and default value initialization. int[] a = new int[8]; a reference array of int a[] a[] length [] [1] [2] [3] [4] [5] [6] [7] 8 length [] [1] [2] [3] [4] [5] [6] [7] 8 [] [1] [2] [3] [4] [5] [6] [7] a[3] is the 4rth element in the array. Java Actually 6: Arrays 6-8/2

Multi-dimensional arrays: arrays of arrays m[] 1. row Declaration, creation and default value initialization. array of int int[][] m = new int[3][2]; m length [] [1] 2 array of array of int length [] [1] [2] 3 m[1] length array of int [] [1] 2 2. row Two-dimensional array m [] [1] [2] [] [1] m[2] array of int 3. row length 2 Element m[2][] No. of elements in 3rd row given by m[2].length [] [1] row column Java Actually 6: Arrays 6-9/2

Storing of array elements One-dimensional array a a[] a[1] a[2] a[3] a[4] a[5] a[6] a[7] Elements of the array a are stored sequentially. [] [1] [2] Two-dimensional array m [] [1] is stored as m[][] m[][1] m[1][] m[1][1] m[2][] m[2][1] Elements of the array m are stored row-wise. Java Actually 6: Arrays 6-1/2

Programming pattern some simple algorithms Find the minimum value in an array: int[] array = new int[n_elements]; // Assume the array is initialized with values. int minvalue = array[]; for (int counter = 1; counter < array.length; ++counter) { if (array[counter] < minvalue) { minvalue = array[counter]; Java Actually 6: Arrays 6-11/2

Find the minimum value in a 2-dimensional array: int[][] matrix = new int[n_elements][m_elements]; // N x M matrix // Assume the array is initialized with values. int minvalue = matrix[][]; for (int counter1 = ; counter1 < matrix.length; ++counter1) { // Find the minimum value in matrix[counter1]; for (int counter2 = ; counter2 < matrix[counter1].length; ++counter2) { if (matrix[counter1][counter2] < minvalue) { minvalue = matrix[counter1][counter2]; Java Actually 6: Arrays 6-12/2

More on initializing of arrays Explicit initialization in the declaration of a one-dimensional array. // integer array with 8 elements int[] array = {1, 3, 49, 55, 58, 41, 52, 3146; // declaration + initialization array[] = {1, 3, 49, 55, 58, 41, 52, 3146; // Compile-time error array = {1, 3, 49, 55, 58, 41, 52, 3146; // Compile-time error Explicit initialization in the declaration of a multi-dimensional array double identitymatrix[][] = { // A 4 x 4 floating-point matrix: {1.,.,.,., // 1. row initialization {., 1.,.,., // 2. row initialization {.,., 1.,., // 3. row initialization {.,.,., 1. // 4. row initialization ; // An array with 4 strings: String[] pets = {"crocodiles", "elephants", "crocophants", "elediles"; char[] chararray = {'a', 'h', 'a'; // An array with 3 characters: Arrays in a multi-dimensional array can have different lengths: double[][] matrix = new double[4][]; // left-most index always specified for (int counter1 = ; counter1 < matrix.length; counter1++) { matrix[counter1] = new double[counter1+1]; Java Actually 6: Arrays 6-13/2

Histogram Problem: Write a program to read floating-point numbers (that represent weights of children), groups them in weight groups and prints a histogram. Type the weights (-199). One weight per line. End with -1. 11.2 13 12.3 82.4 12.9... -1 Weight : Frequency... 1 : *** 11 : * 12 : **... 82 : * 83 :... 199 : ***** Data structure: An array is used to count the weights. Index in the array represents a weight group. Value of an element in the array represents the number of children in this weight group, i.e. the frequency. Algorithm: - Read the weights and place them in the correct weight group. - Find the minimum and the maximum weight register. - For each weight group (from minimum to maximum) print the number of stars that represent the frequency. Java Actually 6: Arrays 6-14/2

Histogram (cont.) import java.util.scanner; public class Histogram { public static void main(string[] args) { int N_ELEMENTS = 2; int[] histarray = new int[n_elements]; Scanner keyboard = new Scanner(System.in); // Read the weights System.out.println("Type the weights (-199). One weight per line. End with -1."); int weight = (int) Math.round(keyboard.nextDouble()); while (weight >= && weight < histarray.length) { histarray[weight]++; weight = (int) Math.round(keyboard.nextDouble()); // Find the index of the element with minimun weight int minindex; for (minindex = ; (minindex < histarray.length) && (histarray[minindex] == ); ++minindex); Java Actually 6: Arrays 6-15/2

// and index of the element with the maximum weight. int maxindex; for (maxindex = histarray.length -1; (maxindex >= ) && (histarray[maxindex] == ); --maxindex); // Print histogram System.out.println("Weight\t:\tFrequency"); for (weight = minindex; weight <= maxindex; weight++) { System.out.print(weight + "\t:\t"); for (int star = 1; star <= histarray[weight]; star++) { System.out.print("*"); System.out.println(); Java Actually 6: Arrays 6-16/2

Enhancedfor loop: for(:) If we are only interested in reading all the values in a collection one by one, we can use the enhanced for loop. The loop cannot be used to change the values in the collection. Syntax: for (loop variable declaration : collection) loop body Example: Integer[] agearray = { 12, 65, 45, 6, 7, 45 ; int numover6 = ; for (int age : agearray) { // Type of loop variable is component type if (age >= 6) { numover6++; System.out.println("Numbers over 6: " + numover6); Program output: Numbers over 6: 3 Java Actually 6: Arrays 6-17/2

Pseudo-random Number Generator To generate a random number we can use the class java.util.random. Such number are called pseudo-random numbers, as they are not really random. How to generate pseudo-random numbers in Java: Random generator = new Random(); // Create an object of class Random Call the method nextint() repeatedly on the Random-object: int newnumber = generator.nextint(); // random number in the interval // [-2 31, 2 31-1] We can specify an argument n in the call to the method nextint() to return an integer number in the interval [, n-1]. newnumber = generator.nextint(11); // random number in [, 1] newnumber = 2 + generator.nextint(11); // random number in [2, 12] newnumber = 2 + 3*generator.nextInt(5); // random number in // {2, 5, 8, 11, 14 Java Actually 6: Arrays 6-18/2

Example: pseudo- number generator import java.util.scanner; // Simulates dice throw using a pseudo-random number generator // and computes the frequency of each dice value (1-6) public class DiceStats2 { public static void main(string[] args) { // Array for counting the frequency of each dice value. int[] frequency = new int[6]; Scanner keyboard = new Scanner(System.in); System.out.print("Enter the number of times to throw the dice: "); int noofthrows = keyboard.nextint(); for (int i = 1; i <= noofthrows; i++) { int dicevalue = (int)(6.*math.random()) + 1; // random numbers 1-6 System.out.println(i + ". dice value: " + dicevalue); // Increment the frequency counter for this throw. frequency[dicevalue-1]++; Java Actually 6: Arrays 6-19/2

for (int dicevalue = 1; dicevalue <= 6; dicevalue++) { System.out.println("No. of times the dice value is " + dicevalue + ": " + frequency[dicevalue-1]); Program out: Enter the number of times to throw the dice: 3 1. dice value: 4 2. dice value: 4... 2999. dice value: 2 3. dice value: 5 No. of times the dice value is 1: 493 No. of times the dice value is 2: 523 No. of times the dice value is 3: 511 No. of times the dice value is 4: 492 No. of times the dice value is 5: 515 No. of times the dice value is 6: 466 Java Actually 6: Arrays 6-2/2