Two-Dimensional Arrays

Similar documents
System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Two-Dimensional Arrays Summer 2010 Margaret Reid-Miller

In this Chapter you ll learn:

Two-Dimensional Arrays. Multi-dimensional Arrays. Two-Dimensional Array Indexing

Unit 6. Loop statements

Iteration CHAPTER 6. Topic Summary

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

1. Use the class definition above to circle and identify the parts of code from the list given in parts a j.

Arrays in Java. Working with Arrays

Patterns in Pascal s Triangle

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

AP Computer Science Java Mr. Clausen Program 9A, 9B

Data Structures and Algorithms Written Examination

COMPUTER SCIENCE. Paper 1 (THEORY)

CMSC 202H. ArrayList, Multidimensional Arrays

API for java.util.iterator. ! hasnext() Are there more items in the list? ! next() Return the next item in the list.

The Interface Concept

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Arrays in Java. data in bulk

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Answers to Review Questions Chapter 7

Project 2: Bejeweled

Part I. The Picture class

Multiplication. Year 1 multiply with concrete objects, arrays and pictorial representations

Java Basics: Data Types, Variables, and Loops

(Eng. Hayam Reda Seireg) Sheet Java

Statements and Control Flow

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

MATHEMATICS GRADE 2 Extension Projects

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

A Concrete Introduction. to the Abstract Concepts. of Integers and Algebra using Algebra Tiles

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

CCSS-M Critical Areas: Kindergarten

Unit 11 Fractions and decimals

GAP CLOSING. Volume and Surface Area. Intermediate / Senior Student Book

VB.NET Programming Fundamentals

Fourth Grade Math Standards and "I Can Statements"

Grade 5 Math Content 1

To Evaluate an Algebraic Expression

The resulting tile cannot merge with another tile again in the same move. When a 2048 tile is created, the player wins.

Example of a Java program

JavaScript: Arrays Pearson Education, Inc. All rights reserved.

Chapter 6: Programming Languages

Introduction to Data Structures

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

1. Kyle stacks 30 sheets of paper as shown to the right. Each sheet weighs about 5 g. How can you find the weight of the whole stack?

Introduction to Java

Homework/Program #5 Solutions

3. How many winning lines are there in 5x5 Tic-Tac-Toe? 4. How many winning lines are there in n x n Tic-Tac-Toe?

Data Structures. Algorithm Performance and Big O Analysis

D06 PROGRAMMING with JAVA

Programming Database lectures for mathema

Unit 1: Family Letter

Pigeonhole Principle Solutions

How to Concatenate Cells in Microsoft Access

ALGEBRA. sequence, term, nth term, consecutive, rule, relationship, generate, predict, continue increase, decrease finite, infinite

K-Means Clustering Tutorial

Moving from C++ to VBA

15-251: Great Theoretical Ideas in Computer Science Anupam Gupta Notes on Combinatorial Games (draft!!) January 29, 2012

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

1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach Robert Sedgewick and Kevin Wayne Copyright /6/11 12:33 PM!

Perimeter, Area and Volume What Do Units Tell You About What Is Being Measured? Overview

J a v a Quiz (Unit 3, Test 0 Practice)

Mobile App Design Project #1 Java Boot Camp: Design Model for Chutes and Ladders Board Game

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

While and Do-While Loops Summer 2010 Margaret Reid-Miller

Measurement. Volume It All Stacks Up. Activity:

Practical Session 4 Java Collections

Chapter 2 Introduction to Java programming

Computer Science III Advanced Placement G/T [AP Computer Science A] Syllabus

Common Data Structures

Software Testing. Definition: Testing is a process of executing a program with data, with the sole intention of finding errors in the program.

INTERSECTION MATH And more! James Tanton

MAT 2170: Laboratory 3

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

The Crescent Primary School Calculation Policy

Computational Mathematics with Python

Part A: Data Definition Language (DDL) Schema and Catalog CREAT TABLE. Referential Triggered Actions. CSC 742 Database Management Systems

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

Efficient Data Structures for Decision Diagrams

2nd Grade Math Common Core Curriculum

AP Computer Science A 2010 Scoring Guidelines

dictionary find definition word definition book index find relevant pages term list of page numbers

DATA STRUCTURES USING C

In This Lecture. SQL Data Definition SQL SQL. Notes. Non-Procedural Programming. Database Systems Lecture 5 Natasha Alechina

CSC 221: Computer Programming I. Fall 2011

8.1. Example: Visualizing Data

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

Hash Tables. Computer Science E-119 Harvard Extension School Fall 2012 David G. Sullivan, Ph.D. Data Dictionary Revisited

Introduction to Programming (in C++) Multi-dimensional vectors. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Solving Problems Recursively

CSE373: Data Structures & Algorithms Lecture 14: Hash Collisions. Linda Shapiro Spring 2016

SQL Programming. CS145 Lecture Notes #10. Motivation. Oracle PL/SQL. Basics. Example schema:

Chapter 2: Elements of Java

Transcription:

Two-Dimensional Arrays Readings: IJP Sections 8.1 8.7 CSE114: Computer Science I Spring 2016 CHEN-WEI WANG

Two-Dimensional Arrays: Motivation Consider a table of distances between cities: Chicago Boston New York Atlanta Miami Dallas Houston Chicago 0 983 787 714 1375 967 1087 Boston 983 0 214 1102 1763 1723 1842 New York 787 214 0 888 1549 1548 1627 Atlanta 714 1102 888 0 661 781 810 Miami 1375 1763 1549 661 0 1426 1187 Dallas 967 1723 1548 781 1426 0 239 Houston 1087 1842 1627 810 1187 239 0 As part of the program for an airline reservation system, the distance of a trip with multiple stop-overs is to be calculated in order to accumulate the milage of frequent flyers. Question: How do you manipulate such information in Java? 2 of 19

Two-Dimensional Arrays: Initialization (1) A 2D array is really an array of arrays 3 of 19

Two-Dimensional Declaring, Creating, Arrays: and Initialization Initializing Using (1) Shorthand Notations You A 2D can array also may use an bearray initialized initializer eitherto at declare, the time create of declaration, and orinitialize after declaration. a two-dimensional array. For example, int[][] array = { {1, 2, 3, {4, 5, 6, {7, 8, 9, {10, 11, 12 ; Same as int[][] array = new int[4][3]; array[0][0] = 1; array[0][1] = 2; array[0][2] = 3; array[1][0] = 4; array[1][1] = 5; array[1][2] = 6; array[2][0] = 7; array[2][1] = 8; array[2][2] = 9; array[3][0] = 10; array[3][1] = 11; array[3][2] = 12; 4 of 19 Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 8

Two-Dimensional Arrays: Lengths (1) For a 2D array, you may query about its size, or sizes of its component arrays. 5 of 19

Two-Dimensional Arrays: Lengths (2) For a 2D array, its components may have different sizes. e.g., Ragged Arrays, cont. 6 of 19

Two-Dimensional Arrays: Assignments For a 2D array, access a slot via its row and column. e.g., 7 of 19

Revisiting the Motivating Example final int Chicago = 0; final int Boston = 1;... final int Houston = 6; int MiamiToBoston = distances[miami][boston]; int BostonToNewYork = distances[boston][newyork]; int MiamiToNewYork = MiamiToBoston + BostonToNewYork; 8 of 19

Two Dimensional Arrays: Example (1) Problem: Given a 2D array a of integers, print out all its values: first row, second row, third row, and so on. for(int row = 0; row < a.length ; row ++) { System.out.print("Row" + row); for(int col = 0; col < a[row].length ; col ++) { System.out.print(a[row][col]); System.out.println(); 9 of 19

Two Dimensional Arrays: Example (2) Problem: Given a 2D array a of integers, calculate the average of its values. int total = 0; int numofelements = 0; for(int row = 0; row < a.length; row ++) { for(int col = 0; col < a[row].length; col ++) { total += a[row][col]; numofelements ++; double average = ((double) total) / numofelements; System.out.println("Average is " + average); Why is the numofelements counter necessary? Divide total by a.length * a[0].length instead? 10 of 19

Two Dimensional Arrays: Example (3) Problem: Given a 2D array a of integers, find out its maximum and minimum values. int max = a[0][0]; int min = a[0][0]; for(int row = 0; row < a.length; row ++) { for(int col = 0; col < a[row].length; col ++) { if (a[row][col] > max) { max = a[row][col]; if (a[row][col] < min) { min = a[row][col]; System.out.println("Maximum is " + max); System.out.println("Minimum is " + min); 11 of 19

Two Dimensional Arrays: Example (4) Problem: Given a 2D array a of integers, find out the row which has the maximum sum. int maxrow = 0; int maxsum = 0; for(int row = 0; row < a.length; row ++) { int sum = 0; for(int col = 0; col < a[row].length; col ++) { sum += a[row][col]; if (sum > maxsum) { maxrow = row; maxsum = sum; System.out.print("Row at index " + maxrow); System.out.println(" has the maximum sum " + maxsum); 12 of 19

Two Dimensional Arrays: Example (5) Problem: Given a 2D array a of integers, determine if all elements are positive. boolean allpos = true; for(int row = 0; row < a.length; row ++) { for(int col = 0; col < a[row].length; col ++) { allpos = allpos && a[row][col] > 0; if (allpos) { /* print */ else { /* print */ Alternatively (with early exit): boolean allpos = true; for(int row = 0; allpos && row < a.length; row ++) { for(int col = 0; allpos && col < a[row].length; col ++) { allpos = a[row][col] > 0; if (allpos) { /* print */ else { /* print */ 13 of 19

Two Dimensional Arrays: Example (6.1) Problem: Given a 2D array a of integers, determine if it is a rectangle (i.e., each row has the same number of columns). if(a.length == 0) { /* empty array can t be a rectangle */ else { /* a.length > 0 */ int assumedlength = a[0].length; boolean isrectangle = true; for(int row = 0; row < a.length; row ++) { isrectangle = isrectangle && a[row].length == assumedlength; if (isrectangle) { /* print */ else { /* print */ Exercise: Change the above code so that it exits from the loop as soon as it is found that the 2-D array is not a rectangle. 14 of 19

Two Dimensional Arrays: Example (6.2) Problem: Given a 2D array a of integers, determine if it is a square (i.e., each row has the same number of columns, and that number is equal to the number of rows of the 2-D array). if(a.length == 0) { /* empty array can t be a square */ else { /* a.length > 0 */ int assumedlength = a[0].length; boolean issquare = a.length == assumedlength ; for(int row = 0; row < a.length; row ++) { issquare = issquare && a[row].length == assumedlength; if (issquare) { /* print */ else { /* print */ Exercise: Change the above code so that it exits from the loop as soon as it is found that the 2-D array is not a square. 15 of 19

Two Dimensional Arrays: Example (7) Problem: Given a 2D array a of integers, print out the upper-left triangular area of elements. Assumption: The input 2D array is of a square shape. for(int row = 0; row < a.length ; row ++) { for(int col = 0; col < a[row].length - row ; col ++) { System.out.print(a[row][col]); System.out.println(); Problem: lower-left triangular area? for(int row = 0; row < a.length ; row ++) { for(int col = 0; col <= row ; col ++) { System.out.print(a[row][col]); System.out.println(); Exercises: upper-right triangle? lower-right triangle? 16 of 19

Two-Dimensional Arrays: Example (8) Consider the tic-tac-toe game: 17 of 19

Index (1) Two-Dimensional Arrays: Motivation Two-Dimensional Arrays: Initialization (1) Two-Dimensional Arrays: Initialization (1) Two-Dimensional Arrays: Lengths (1) Two-Dimensional Arrays: Lengths (2) Two-Dimensional Arrays: Assignments Revisiting the Motivating Example Two Dimensional Arrays: Example (1) Two Dimensional Arrays: Example (2) Two Dimensional Arrays: Example (3) Two Dimensional Arrays: Example (4) Two Dimensional Arrays: Example (5) Two Dimensional Arrays: Example (6.1) Two Dimensional Arrays: Example (6.2) 18 of 19

Index (2) Two Dimensional Arrays: Example (7) Two-Dimensional Arrays: Example (8) 19 of 19