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

Similar documents
Chapter 9 Introduction to Arrays. Fundamentals of Java

ARRAYS, RECURSION, AND COMPLEXITY

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

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Creating Two-dimensional Arrays

Lab Assignment Three

Lesson 35..Two-Dimensional Arrays

TOPICS TO COVER:-- Array declaration and use.

Class C{ int a; } what variables below are objects : a. C c; b. String str; c. Scanner scanner; d. int num; e. float f;

COSC 1P03. Chapter 1 Arrays. Introduction to Data Structures 1.2

CSE 230 Intermediate Programming in C and C++ Arrays and Pointers

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 25, 2016

type arrayname [ size type arrayname [ size ] = { item ,, item size size

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

Arrays: Higher Dimensional Arrays. CS0007: Introduction to Computer Programming

UNIT-I Fundamental Notations

For example, let s say we define an array of char of size six:

Selected Questions from by Nageshwara Rao

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

Declaring a 2D Array

3. Convert 2E from hexadecimal to decimal. 4. Convert from binary to hexadecimal

Array. Array Declaration:

Array. Prepared By - Rifat Shahriyar

Object Oriented Programming. Java-Lecture 6 - Arrays

2. Each element of an array is accessed by a number known as a(n) a. a. subscript b. size declarator c. address d. specifier

Exam 2. CSC 121 TTH Class. Lecturer: Howard Rosenthal. April 26, 2016

Programming for Electrical and Computer Engineers. Pointers and Arrays

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Arrays and Array Lists. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington

Scope of this lecture

Arrays in Java Using Arrays

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

CSEN 202: Introduction to Computer Programming Spring term Final Exam

Arrays to the rescue!

1 Short Answer (10 Points Each)

ESC101N: Fundamentals of Computing End-sem st semester

Exercises Software Development I. 06 Arrays. Declaration, Initialization, Usage // Multi-dimensional Arrays. November 14, 2012

University of Palestine. Mid Exam Total Grade: 100

Arrays in Java Multi-dimensional Arrays

Module 6: Array in C

Loops. EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG

CS 113 MIDTERM EXAM 2 SPRING 2013

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Sorting and Searching Algorithms

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. A single variable can only hold one value. Declared using [] operator:

Arrays. Chapter 7 Part 3 Multi-Dimensional Arrays

UNIT 2 ARRAYS 2.0 INTRODUCTION. Structure. Page Nos.

Maltepe University Computer Engineering Department. BİL 133 Algorithms and Programming. Chapter 8: Arrays

Chapter 10. Arrays and Strings

Repetition Structures

Inf1-OP. Arrays 1. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. January 30, School of Informatics

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174

All answers will be posted on web site, and most will be reviewed in class.

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

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

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

Java Review Outline. basics exceptions variables arrays modulo operator if statements, booleans, comparisons loops: while and for

Inf1-OOP. Arrays 1. Perdita Stevens, adapting earlier version by Ewan Klein. January 11, School of Informatics

COMPUTER SCIENCE. 4. Arrays. Section 1.4.

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

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

7.1. Chapter 7: Arrays Hold Multiple Values. Array - Memory Layout. Array Terminology. Array Terminology

BITG 1113: Array (Part 1) LECTURE 8

Inf1-OOP. Arrays. Many Variables of the Same Type. Arrays Introduction to Arrays Arrays in Java Shuffling a Deck Multidimensional Arrays Summary/Admin

BITG 1233: Array (Part 1) LECTURE 8 (Sem 2, 17/18)

1 Short Answer (10 Points Each)

Practice Midterm 1. Problem Points Score TOTAL 50

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

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

Motivation of Loops. Loops. The for Loop (1) Learning Outcomes

FORM 2 (Please put your name and form # on the scantron!!!!)

Arrays in C. Data and File Structures Laboratory. DFS Lab (ISI) Arrays in C 1 / 1

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

Topics. Java arrays. Definition. Data Structures and Information Systems Part 1: Data Structures. Lecture 3: Arrays (1)

Arrays. Structure programming. Section-(6) Array Initialization. <Type> [] identifier;

Inf1-OP. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

Lecture 17. For Array Class Shenanigans

Module 5. Arrays. Adapted from Absolute Java, Rose Williams, Binghamton University

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

CSCI 136 Written Exam #1 Fundamentals of Computer Science II Spring 2013

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

AP Computer Science. Arrays. Copyright 2010 by Pearson Education

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

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

Lecture 2. Two-Dimensional Arrays

Outline Arrays Examples of array usage Passing arrays to functions 2D arrays Strings Searching arrays Next Time. C Arrays.

CS 302: Introduction to Programming in Java. Lecture 9

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

Arrays. Inf1-OP. Arrays. Many Variables of the Same Type. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

CS159 Midterm #1 Review

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

Introduction to Programming Using Java (98-388)

Introduction to Object-Oriented Programming

5.12 EXERCISES Exercises 263

Lab #10 Multi-dimensional Arrays

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

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

Transcription:

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 10 INTRODUCTION TO ARRAYS EXERCISE 10.1 1. An array can contain many items and still be treated as one thing. Thus, instead of having many variables for many items, an array requires just one variable and an operator to access each item within it. To access an item in an array, the programmer uses the subscript []. wages 78.50 68.50 wages[0] wages[1] wages[2] wages[3] wages[4] EXERCISE 10.2 1. a. 23 b. 12 c. 156 Because each of these positions is outside of the range of allowable positions for this array, a range-bound error occurs, and Java throws an array index out of bounds exception. EXERCISE 10.3 1. for (int i = 0; i < a.length; i++) System.out.println(a[i]); for (int i = a.length - 1; i >= 0; i--) System.out.println(a[i]); int pos = 0; for (pos = 0; pos < a.length; pos++) if (a[pos] < 0) break; a. Replaces all the numbers in the array with their absolute values. b. Builds a new string with the items in the array. These items can be anything. 1

5. You can use the variable length when you want to visit all the items in an array. This reference does the job for any array, so its use makes the code more portable and maintainable. EXERCISE 10.4 1. a. double[] doublearray = new double[15]; b. String[] stringarray = new String[20]; An initializer list allows the program to specify the values that initially occupy positions in an array. An example of its use is int[] a = {2, 4, 6; a. int[] scores = {100, 90, 75, 60, 88; b. double[] rates = {0.12, 0.05, 0.15; c. String[] names = {"Martin", "Osborne"; It is better to use the form <type>[] <variable> when declaring an array so as not to confuse it with the form <type> variable when declaring ordinary variables. EXERCISE 10.5 1. When a programmer tries to access an item in an array cell whose index is greater than or equal to the array s logical size, this item is garbage (not currently part of the useful data in the program). The value returned could be an arbitrary number if we have an array of numbers or even null if we have an array of objects. An application that inputs an arbitrary number of data items from a user would need an array that could accommodate all the items. If the number of items varies, so will the logical size of the array, and the array will not necessarily be full. EXERCISE 10.6 0. Parallel arrays are two or more arrays that have the same length and use the same index values to establish logical connections among their items. 1. One might use parallel arrays to represent a phone book. The names occupy one array and the phone numbers occupy the other array. String[] names = new String[50]; int[] ages = new int[50]; String[] ssn = new String[50]; for (int i = 0; i < names.length; i++) System.out.printf("%-20s%3d", names[i], numbers[i]); int expos = new int[10]; int powers = new int[10]; for (int i = 0; i < expos.length; i++){ expos[i] = i; powers[i] = Math.pow(2, i); 2

EXERCISE 10.7 1. a. for (String str : abc) System.out.println(str); b. for (String str : abc) if (target.equals(str)){ found = true; break; An enhanced for loop would not work when traversing an array from the last position to the first position. It would also not work when replacing an element at a given position in an array. EXERCISE 10.8 1. The assignment operator makes the two variables refer to the same array object. As with other objects, arrays are not copied when the assignment operator is used. Thus, one must instantiate a new array of the same type and length as the original, transfer the items to the new array, and return the new array. double average(double[]a){ double sum = 0; for (int i : a) sum += i; return sum / a.length; int[] subarray(int[] a, int first, int last){ int[] result = new int[last first + 1]; for (int i = first; i <= last; i++) result[i first] = a[i]; return result; 5. Point search(int[][] a, int target){ int row = 0; int col = 0; for (row = 0; row < a.length; row++) for (col = 0; col < a[row].length; col++) if (a[row][col] == target) return new Point(row, col); return new Point(row, col); EXERCISE 10.9 1. Student gethighstudent(student[] students){ Student highest = null; for (int i = 0; i < studentcount; i++) if (highest == null students[i].gethighscore() > highest.gethighscore()) highest = students[i]; 3

return highest; The JVM will throw an array index out of bounds exception after the scores for the five students are displayed. The reason this happens is that the elements in the array after position 4 are null, and the array s length is used in the output loop. EXERCISE 10.10 1. private class AveScoreListener implements ActionListener{ public void actionperformed(actionevent e){ if (model.size() == 0){ JOptionPane.showMessageDialog(TestScoresView.this, "No student is available"); return; int ave = model.getclassaverage(); JOptionPane.showMessageDialog(TestScoresView.this, "The average score is " + ave); The advantage of using a single listener class for all button events is that only a single instance needs to be created and attached to all the buttons. The disadvantages are that the actionperformed method consists of a complex multiway if statement to handle all of the cases, and the responsibilities for handling many tasks are located in one object. REVIEW QUESTIONS Written Questions 1. a. Valid b. Valid c. Invalid d. Invalid e. Invalid f. Valid g. Valid h. Invalid i. Invalid j. Valid a. Valid, 6 b. Valid, 3 c. Valid, 7 d. Invalid, index position out of range e. Valid, 9 f. Invalid, index position must be an integer 4

a. An array of int variable is declared, but is set to an array of double. b. A double, 1.5, cannot be used to specify the length of the array. c. A negative number, 10, cannot be used to specify the length of the array. d. A one-dimensional array object cannot be assigned to a variable of a twodimensional array type. int selectrandom(int [] a){ Random rand = new Random(); int index = rand.nextint(a.length)); return a[index]; 5. int[][] a = new int[5][4]; 6. for (int i = 0; i < a.length; i++) for (int j = 0; j < a[i].length; j++) a[i][j] = 1 + (int) (math.random() * 20); 5