Arrays in Java Using Arrays

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

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

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

Array basics. Readings: 7.1

Array basics. How would you solve this? Arrays. What makes the problem hard? Array auto-initialization. Array declaration. Readings: 7.

CSC 1051 Arrays - Review questions

University of Palestine. Mid Exam Total Grade: 100

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

Controls Structure for Repetition

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

Decisions in Java IF Statements

ESC101 : Fundamental of Computing

COS 126 General Computer Science Spring Written Exam 1

Computer Science is...

CS S-08 Arrays and Midterm Review 1

1 Short Answer (10 Points Each)

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

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

Introduction to Object-Oriented Programming

Algorithms and Problem Solving

Midterm Examination (MTA)

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

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

CIS November 14, 2017

CIS 1068 Netflix Challenge New assignment posted soon Lab grades November 14, 2017

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

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

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

Building Java Programs

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

1.3b Type Conversion

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Computação I. Exercises. Leonardo Vanneschi NOVA IMS, Universidade Nova de Lisboa. Leonardo Vanneschi Computação I NOVA IMS

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

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

Chapter 6 Single-dimensional Arrays

Object Oriented Programming. Java-Lecture 6 - Arrays

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

Repetition CSC 121 Fall 2014 Howard Rosenthal

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

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

Loops and Expression Types

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.

Java Programming: from the Beginning

Final Exam. COMP Summer I June 26, points

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

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

CS 113 MIDTERM EXAM 2 SPRING 2013

Fall 2005 CS 11 Final exam Answers

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

Lab Assignment Three

Searching & Sorting in Java Bubble Sort

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

CS115 Principles of Computer Science

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each

Algorithm efficiency can be measured in terms of: Time Space Other resources such as processors, network packets, etc.

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Last Class. While loops Infinite loops Loop counters Iterations

Module 7: Arrays (Single Dimensional)

AP COMPUTER SCIENCE A DIAGNOSTIC EXAM. Multiple Choice Section Time - 1 hour and 15 minutes Number of questions - 40 Percent of total grade - 50

Arrays. Eng. Mohammed Abdualal

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

Control Structures: if and while A C S L E C T U R E 4

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

Computer Science 1 Ah

Lecture 9: Arrays. Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp. Copyright (c) Pearson All rights reserved.

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

Computer Programming I - Unit 5 Lecture page 1 of 14

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

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Chapter 4: Control structures. Repetition

New Concepts. Lab 7 Using Arrays, an Introduction

Chapter 17. Iteration The while Statement

Handout 5 cs180 - Programming Fundamentals Spring 15 Page 1 of 8. Handout 5. Loops.

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

Assignment 2.4: Loops

Section 003 Fall CS 170 Exam 2. Name (print): Instructions:

Arrays in Java Multi-dimensional Arrays

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

CSCI 135 Exam #2 Fundamentals of Computer Science I Fall 2013

CS1150 Principles of Computer Science Arrays

Sample Midterm Exam #2

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

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

COE 212 Engineering Programming. Welcome to the Final Exam Thursday December 15, 2016

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 10 INTRODUCTION TO ARRAYS

CSE 373 Section Handout #1 Numeric Data

1 Short Answer (15 Points Each)

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

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

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

Chapter 4: Control structures

All classes in a package can be imported by using only one import statement. If the postcondition of a method is not met, blame its implementer

Chapter 8 Multi-Dimensional Arrays

Lecture 14 CSE11 Fall 2013 For loops, Do While, Break, Continue

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

Chapter 7 Single-Dimensional Arrays

Transcription:

Recall Length of an Array Arrays in Java Using Arrays Once an array has been created in memory, its size is fixed for the duration of its existence. Every array object has a length field whose value can be obtained by appending.length to the array identifier. double[] price = new double[100]; // create array with 100 elements int len = price.length; // the.length will be 100 Since all arrays start numbering at zero, the length is always one greater than the highest index. For example, an array with 100 elements will have a length of 100, but the index will range from 0 to 99. Traversing Arrays To access each element in an array, a counted, or for loop, is frequently used. Suppose we have an array of 100 boolean values, automatically initialized to false by default. To change all of these to true, we could write boolean[] flags = new boolean[100]; for (int i = 0; i < flags.length; i++) flags[i] = true; Note that we have used the flags.length to determine the upper bound of the loop. As we previously noted, the.length field will return a value one greater (in this case, 100) than the maximum index of the array (in this case, 99), which is why our loop must use i < flags.length to avoid running past the end of the array. If we attempt to use an index that is outside of the range of the array, Java will throw an exception (i.e., report an error). Comparing Arrays Arrays are objects, and as such, they have the same limitations we experience with other objects. One of those involves the notion of equality. The array variable is a reference to an array object. In other words, it points to a location in memory which holds the array and its data. We must keep this in mind when using the assignment statement (=) and the equality operator (==). For example, suppose we have made the following declaration: int[] p = 1, 2, 3, 4, 5; int[] q = 1, 2, 3, 4, 5; p q 1 2 3 4 5 1 2 3 4 5 31. Oct. 2012 Page 1 of 7

Through common sense, it would be reasonable to say they arrays are equal. They contain the same number and type of elements, and each corresponding element contains the same value. Nonetheless, if we were to test their equality, System.out.println(p == q); // false The result would be false. The reason is that the variables p and q are references to memory locations, or addresses in memory. Since each array is distinct in memory, it must have a unique address, so they are definitely not equal. Similarly, using the assignment operator (=) could produce an unexpected situation. p = q; q[0] = 100; System.out.println(p[0]); // outputs 100 System.out.println(p == q); // now true In this case, the variables p and q now point to the same memory location, and the data contained in the original p array is forever lost. p q 1 2 3 4 5 Lost Data! 100 2 3 4 5 Arrays as Method Parameters Like other variables and objects in Java, arrays can be parameters of methods, and can be returned by methods. Since the array variable is a reference, the method will make a copy of the reference, so the original cannot be changed by the method. The referenced data, however, can and will be changed by the method unless you keep this in mind (and sometimes you want to change array data using a method, so this is desirable). public static double[] join (double[] a, double[] b) double[] result = new double [a.length + b.length]; int i, j; for (i = 0; i < a.length; i++) result[i] = a[i]; for (j = 0; j < b.length; i++, j++) result[i] = b[j]; return result; Note that when introducing arrays, we discussed that their size was fixed. While this is true, it is possible to dynamically create a new array of any size, and if necessary, abandon the original array (which, in effect, allows a programmer to dynamically alter the size of an array). 31. Oct. 2012 Page 2 of 7

Another example, the method swap shown below will switch the values of two elements in an array of double values. When we tried this using variables, it failed. It succeeds now because an array is a reference to a memory location. public static void swap (double[] list, int i, int j) double temp = list[i]; list[i] = list[j]; list[j] = temp; To show the effect of this code, consider the array masses shown below: masses 7.3 9.1 3.3 4.7 6.0 If we then execute the statement swap(masses, 1, 4); the values of masses[1] and masses[4] will be switched. masses 7.3 6.0 3.3 4.7 9.1 31. Oct. 2012 Page 3 of 7

Exercises 1. What would be printed by the following program fragment? int[] list = new int[4]; for (int i = 0; i < list.length; i++) list[i] = 3 i; System.out.println(list[1]+2); System.out.println(list[1+2]); System.out.println(list[1]+list[2]); 2. Suppose that an array sample has been declared as follows: int[] sample = new int[10]; Write one or more statements to perform each task. a) Initialize all of the elements to one (1). b) Switch the values at either end of the array. c) Change any negative values to positive values. d) Set the variable samplesum to the sum of the values of all the elements. e) Print the contents of the odd-numbered locations. 3. Write a method max that has one double array parameter. The method should return the value of the largest element in the array. 4. Complete the definition of the method equals so that it returns true if and only if its two array parameters are identical in every way. public static boolean equals (double[] a, double[] b) 5. Write a program that repeatedly prompts the user to supply scores (out of 10) on a test. The program should continue to ask the user for marks until a negative value is supplied. Any values greater than ten should be ignored. Once the program has read all the scores, it should produce a table with the following headings (and automatically fill in the rest of the table): Score # of Occurrences The program should then calculate the mean score, rounded to one decimal place. 31. Oct. 2012 Page 4 of 7

Solutions 1. What would be printed by the following program fragment? int[] list = new int[4]; for (int i = 0; i < list.length; i++) list[i] = 3 i; System.out.println(list[1]+2); System.out.println(list[1+2]); System.out.println(list[1]+list[2]); 4 0 3 2. Suppose that an array sample has been declared as follows: int[] sample = new int[size]; where SIZE is some constant value. Write one or more statements to perform each task. a) Initialize all of the elements to one (1). sample[i] = 1; b) Switch the values at either end of the array. int temp = sample[0]; sample[0] = sample[sample.length 1]; sample[sample.length 1] = temp; c) Change any negative values to positive values. sample[i] = (int)math.abs(sample[i]); d) Set the variable samplesum to the sum of the values of all the elements. int samplesum = 0; samplesum += sample[i]; e) Print the contents of the odd-numbered locations. if (i % 2!= 0) System.out.println(sample[i]); 31. Oct. 2012 Page 5 of 7

3. Write a method max that has one double array parameter. The method should return the value of the largest element in the array. public static double max (double[] array) double max = array[0]; for (i = 0; i < array.length; i++) if (array[i] > max) max = array[i]; return max; 4. Complete the definition of the method equals so that it returns true if and only if its two array parameters are identical in every way. public static boolean equals (double[] a, double[] b) boolean equals = (a.length == b.length); // passed first test, now check elements for (int i = 0; i < a.length; i++) // a single failure means total failure equals = equals && (a[i] == b[i]); return equals; 31. Oct. 2012 Page 6 of 7

5. Write a program that repeatedly prompts the user to supply scores (out of 10) on a test. The program should continue to ask the user for marks until a negative value is supplied. Any values greater than ten should be ignored. Once the program has read all the scores, it should produce a table with the following headings (and automatically fill in the rest of the table): Score # of Occurrences The program should then calculate the mean score, rounded to one decimal place. class ArraysEx5 public static void main(string [] args) // possible scores are 0 through 10, all integer int[] countscores = new int[11]; int score, totalscores = 0, numscores = 0; do System.out.println("Please enter a mark out of 10 (negative to quit)"); score = In.getInt(); if (0 <= score && score <= 10) countscores[score]++; // increment the count of that score while (score >= 0); // display scores, adding at the same time System.out.println("Score # of Occurrences"); System.out.println("===== ================"); for (int i = 0; i <= 10; i++) totalscores += i * countscores[i]; numscores += countscores[i]; System.out.println(i + " " + countscores[i]); // The format command below is an alternative to the basic println. // You can research this on your own if you wish to experiment. //System.out.format("%5d %d%n", i, countscores[i]); System.out.println(); System.out.println("Average score: " + ((float)totalscores/(float)numscores)); // The format command below is an alternative to the basic println. // You can research this on your own if you wish to experiment. //System.out.format("Average score: %.1f%n", ((float)totalscores/(float)numscores)); 31. Oct. 2012 Page 7 of 7