Arrays. 1 Index mapping

Similar documents
University of Palestine. Mid Exam Total Grade: 100

Lecture 5: Methods CS2301

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Lecture 15. Arrays (and For Loops)

CS1150 Principles of Computer Science Methods

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

This page intentionally left blank

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

ICOM 4015 Advanced Programming Laboratory. Chapter 1 Introduction to Eclipse, Java and JUnit

Loops and Expression Types

BSc (Hons) Computer Science with Network Security/ BSc (Hons) Software Engineering/ BSc (Hons) Web Technologies. Examinations for 2016 Semester 1

Object Oriented Programming. Java-Lecture 6 - Arrays

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

CS1150 Principles of Computer Science Methods

Methods. Every Java application must have a main method.

More on Classes. 1 tostring

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

Methods. Bok, Jong Soon

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

Activity 6: Loops. Content Learning Objectives. Process Skill Goals

Loops. CSE 114, Computer Science 1 Stony Brook University

M e t h o d s a n d P a r a m e t e r s

Functions. x y z. f (x, y, z) Take in input arguments (zero or more) Perform some computation - May have side-effects (such as drawing)

CSE 201 JAVA PROGRAMMING I. Copyright 2016 by Smart Coding School

A Foundation for Programming

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

COMP 110/L Lecture 13. Kyle Dewey

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Review of Basic Java

CSCI 135 Exam #0 Fundamentals of Computer Science I Fall 2012

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

COMP 110 Programming Exercise: Simulation of the Game of Craps

Nested Loops. A loop can be nested inside another loop.

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

Condi(onals and Loops

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

H212 Introduction to Software Systems Honors

TA office hours are over after this week, but Dan and Maja will still be around for the next month

Slide 1 Side Effects Duration: 00:00:53 Advance mode: Auto

COS 126 General Computer Science Spring Written Exam 1

CS S-08 Arrays and Midterm Review 1

Lesson 36: for() Loops (W11D1)

Simple Java Reference

Computer Programming: C++

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

COS 126 Exam Review. Exams overview Example programming exam Example written exam questions (part 1)

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

JAVA OPERATORS GENERAL

CHAPTER 7 OBJECTS AND CLASSES

13 th Windsor Regional Secondary School Computer Programming Competition

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

Java Basic Programming Constructs

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

The University of Western Ontario Department of Computer Science Computer Science 1026a Midterm Exam 2 hours

Final. Your Name CS Fall 2014 December 13, points total Your Instructor and Section

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Q5. What values are stored in the array at the comment in main? Note that the incrementall returns void, but does take an int[] parameter.

Selected Sections of Applied Informatics LABORATORY 0

Arrays. Eng. Mohammed Abdualal

Java Simple Data Types

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Computer Science is...

CS 231 Data Structures and Algorithms, Fall 2016

Advanced Computer Programming

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

B.V. Patel Institute of BMC & IT, UTU 2014

Java Coding 3. Over & over again!

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

Java Simple Data Types

Chapter 6 Methods. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

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

What are the differences between the Set interface and the List interface?

CS110: PROGRAMMING LANGUAGE I

CIS133J. Working with Numbers in Java

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

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

A Bad Idea Monday, April 16, :23 AM

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

COMP-202. Recursion. COMP Recursion, 2013 Jörg Kienzle and others

Variables and Java vs C++

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

Birkbeck (University of London) Software and Programming 1 In-class Test Mar Answer ALL Questions

Methods. CSE 114, Computer Science 1 Stony Brook University

SAMPLE QUESTIONS FOR DIPLOMA IN INFORMATION TECHNOLOGY; YEAR 1

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

COS 126 Midterm 1 Written Exam Fall 2012

CS 170 Exam 2. Version: A Fall Name (as in OPUS) (print): Instructions:

Section 2: Introduction to Java. Historical note

CISC-124. Casting. // this would fail because we can t assign a double value to an int // variable

The list abstract data type defined a number of operations that all list-like objects ought to implement:

Java Socket Workshop. July Purpose of this workshop:

Activity 6: Loops. Content Learning Objectives. Process Skill Goals

Handout 4 Conditionals. Boolean Expressions.

Anatomy of a Java Program: Comments

COMPUTER APPLICATIONS

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Lecture 14. 'for' loops and Arrays

Full file at

Transcription:

Arrays 1 Index mapping You are expected already to have a good understanding of arrays. We examine some array techniques in more detail, beginning with index mapping. Index mapping is a technique for compact array code by employing rich expressions in indices. Suppose, say, we want read a text and print the frequencies of word-lengths in the text. An example of output is: 1-letter words: 3 2-letter words: 5 3-letter words: 9 4-letter words: 4 6-letter words: 1 class WordCount { public static void main(string[] args) { int[] count = new int[20]; // word lengths up to 19, say // zero counts int i = 0; while (i<count.length) { count[i] = 0; i++; // Read words & keep track of frequencies while (! Console.endOfFile()) { String word = Console.readToken(); count[word.length()]++; // Print result Arrays J. M. Morris Page 14.1

i = 1; while (i<count.length) { if (count[i]>0) System.out.println(i + "-letter words: " + count[i]); i++; Each word read is mapped to the index of the appropriate component of count[] component i of count[] records the number of words of length i (component 0 is not used). Each word is read into string variable word, and hence the word s length is word.length(). If this is 4, say, then we must increment word[4]. Note that the length operator for arrays has no brackets, unlike that for arrays. 2 Accessing arrays using for-each loops For-each loops provide a convenient way to access all the values in an array. For example, suppose a program contains the integer array myarray; the values in myarray are printed using the following for-each loop for (int k: myarray) System.out.println(k); We could have also expressed this a for-loop as follows, although it is a little more cumbersome: for (int i=0; i<myarray.length; i++) System.out.println(myArray[i]); The for-loop is in turn just a shorthand for the following while-loop int i = 0; while (i<myarray.length) { System.out.println(myArray[i]); i++; Arrays J. M. Morris Page 14.2

While loops are completely general, for-loops are more restrictive but a little more convenient when, and for-each loops are again more convenient but are even more limited in their applicability. For example, it is not possible to use a for-each loop to assign a value to every element of an array. None of the loops in the word count program above can be written using a foreach loop. 3 Arrays as objects Java treats arrays as objects. Hence an array variable does not literally contain an array, but a reference to one. For example, the declaration below can be envisaged as shown: int[] b = {3, 5, 6, 4, 5; b 3 5 6 4 5 0 1 2 3 4 Suppose we have if addition to the declaration of b above, array c declared as follows: int[] c = {5, 7, 9; c 5 7 9 Then the assignment b = c; b c 5 7 9 is effected by copying the reference to the array, as illustrated. 4 Arrays as parameters and return types Arrays may occur as parameters of methods, or as return types, as in the following example to make a copy of an array. static int[] copy(int[] b) { int[] r = new int[b.length]; for (int i=0; i<r.length; i++) r[i] = b[i]; return r;... int[] c = {5, 7, 9; Arrays J. M. Morris Page 14.3

int[] d = copy(c); // note: no "= new int[...]" needed here The array parameter in the following example is assigned to in the method body. As an exercise trace the execution of the program; state the output produced, justify it, and then test your answer (you may be surprised at first!) static void incrementall(int[] b) { for (int i=0; i<b.length; i++) b[i]++;... int[] c = {5, 7, 9; incrementall(c); System.out.println(c[0] + " " + c[1] + " " + c[2]); 5 Command line arguments You can pass arguments to a program from the command line. The arguments are formed into an array of strings and passed to the program. For example, if we issue the command java MyProgram Bill Smith 15 3 1978 where class MyProgram has method public static void main(string[] args) the following array is made available in main() args Bill Smith 15 3 1978 0 1 2 3 4 Note that every item is passed as a string, even the integers (you can convert them back to type int using Integer.parseInt()). We illustrate with a program which sums a list of integers supplied at the command line. The following is a typical invocations of the program: java AddInts 7 13-4 10 13 class AddInts { public static void main(string[] args) { int sum = 0; Arrays J. M. Morris Page 14.4

for (String s: args) { sum = sum + Integer.parseInt(s); System.out.println(sum); Warning: remember that command line arguments are not read from the keyboard by the executing program they are supplied in the command line when the program is invoked. Arrays J. M. Morris Page 14.5