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



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

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

Sample CSE8A midterm Multiple Choice (circle one)

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:

Introduction to Java

(Eng. Hayam Reda Seireg) Sheet Java

Arrays in Java. Working with Arrays

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

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

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

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

In this Chapter you ll learn:

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Unit 6. Loop statements

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to Computer Programming, Spring Term 2014 Practice Assignment 3 Discussion

Iteration CHAPTER 6. Topic Summary

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

Two-Dimensional Arrays Summer 2010 Margaret Reid-Miller

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

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

Arrays. Introduction. Chapter 7

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Part I. Multiple Choice Questions (2 points each):

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

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Example of a Java program

AP Computer Science Static Methods, Strings, User Input

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

Homework/Program #5 Solutions

Statements and Control Flow

AP Computer Science Java Subset

public static void main(string[] args) { System.out.println("hello, world"); } }

12-6 Write a recursive definition of a valid Java identifier (see chapter 2).

CMSC 202H. ArrayList, Multidimensional Arrays

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

LOOPS CHAPTER CHAPTER GOALS

The following program is aiming to extract from a simple text file an analysis of the content such as:

Building Java Programs

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

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

Chapter 2 Introduction to Java programming

Project 2: Bejeweled

Building Java Programs

Building Java Programs

CS 106 Introduction to Computer Science I

arrays C Programming Language - Arrays

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Topic 11 Scanner object, conditional execution

VB.NET Programming Fundamentals

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

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

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

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

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

COMPUTER SCIENCE. Paper 1 (THEORY)

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

Building Java Programs

Java Crash Course Part I

Arrays in Java. data in bulk

Continuous Integration Part 2

Introduction to Java. CS 3: Computer Programming in Java

Object Oriented Software Design

JAVA ARRAY EXAMPLE PDF

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

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

Introduction to Data Structures

Chapter 5. Recursion. Data Structures and Algorithms in Java

Variables, Constants, and Data Types

Basic Programming and PC Skills: Basic Programming and PC Skills:

Solving Problems Recursively

CS170 Lab 11 Abstract Data Types & Objects

Conditional Statements Summer 2010 Margaret Reid-Miller

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

Recursion and Recursive Backtracking

Explain the relationship between a class and an object. Which is general and which is specific?

Moving from CS 61A Scheme to CS 61B Java

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

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

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

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

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Common Beginner C++ Programming Mistakes

IRA EXAMPLES. This topic has two examples showing the calculation of the future value an IRA (Individual Retirement Account).

13 File Output and Input

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

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Data Structures In Java

8.1. Example: Visualizing Data

Pemrograman Dasar. Basic Elements Of Java

Java Basics: Data Types, Variables, and Loops

Building a Multi-Threaded Web Server

Transcription:

Multi-dimensional Arrays The elements of an array can be any type Including an array type So int 2D[] []; declares an array of arrays of int Two dimensional arrays are useful for representing tables of data with rows and columns Three dimensional arrays are useful for representing volume data with three coordinates x, y, and z Two-Dimensional Arrays A 2 dimensional array is declared and allocated like this: int a[][] = new int[3][4]; a is an array of 3 arrays of int a[0] is an array of 4 ints a[1] is an array of 4 ints a[2] is an array of 4 ints Two-Dimensional Array Indexing Array elements are access by providing a value for all subscripts. a[0][0] a[0][1] a[0][2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3] The first subscript represents the row The second subscript represents the column Two-Dimensional Array Example // Division Table class Divide { public static void main(string[] args) { double[][] data = new double[10][5]; for(int i = 0; i < data.length; i++) { for(int j = 0; j < data[i].length; j++) { data[i][j] = (double)i / j; for(int i = 0; i < data.length; i++) { for(int j = 0; j < data[i].length; j++) { System.out.print(data[i][j] + " "); System.out.println();

Two-Dimensional Array Initializer Remember, we can initialize a single dimensional array int temperature[] = {32, 35, 38, 36, 38, 35, 40; We can also initialize two-dimensional arrays int temperature[][] = {{32, 58, {35, 60, {38, 59, {36, 63, {38, 61, {35, 65, {40, 68; Irregular Arrays 2-dimensional arrays don't have to be 'rectangular' int a[][] = {{2, 5, {3, 4, 0, {3, {4, 5; a[0] a[1] a[2] a[3] array of 2 ints array of 3 ints array of 1 int array of 2 ints Conway's Game of Life This game was originally developed to simulate certain kinds of growth It is "played" on a rectangular grid, like a checkerboard Each cell of the board is either alive or dead Live cells are marked with an 'X' Rules for the Game of Life Each cell is either empty or alive Each cell is at the center of a 3x3 grid of cells, which contains the cell's 8 neighbors A cell that is empty at time t becomes alive at time t+1 if and only if exactly 3 of its neighbors were alive at time t. A cell that is alive at time t remains alive at time t+1 if and only if 2 or 3 of its neighbors were alive at time t. Otherwise, it dies for lack of company (<2) or overcrowding (>3) The simulation is conducted, in principle, on an infinite grid.

Requirements Use a finite grid instead of an infinite one Treat borders as lifeless zones User will specify grid size, which will always be square The user will specify the number of steps to simulate Get the initial configuration by reading *'s and dots from the console The program will echo the initial configuration and then display each subsequent configuration. Top Level PsuedoCode Read in the size of the grid Read in the initial generation Read in the number of generations to simulate Print the current generation For the specified number of generations Advance one generation Print the generation end for loop Advance One Generation For each cell compute the number of neighbors apply the game rules to decide if the cell should be alive or dead in the next generation end for loop Compute the number of neighbors visit each cell in the 3x3 subarray around the cell keep a count of how many of those are alive if the center cell is alive then return 1 less than the count found else return the count found

Refined Top Level PsuedoCode Read in the size of the grid Create 2 arrays, currentgen and nextgen Read in the initial generation into currentget Read in the number of generations to simulate Print the current generation For the specified number of generations Update nextgen using currentgen Swap nextgen and currentgen Print currentgen end for loop Refined Advance One Generation input: currentgen and nextgen output: updated nextgen For each cell in currentgen compute the number of neighbors apply the game rules to decide if the cell should be alive or dead in the next generation store the result, alive or dead, in the corresponding cell in nextgen end for loop GameOfLife: main part 1 //GameOfLife.java - Conway's Game of Life import tio.*; class GameOfLife { public static void main(string[] args) { // read in the size of the grid and create arrays int size = 10; // fix at 10 for testing boolean[][] currentgeneration, nextgeneration; currentgeneration = new boolean[size][size]; nextgeneration = new boolean[size][size]; readinitialgeneration(currentgeneration); GameOfLife: main part 2 // read in the number of generations to simulate int cycles = 4; // fix at 4 for testing printstate(currentgeneration); for (int i = 0; i < cycles; i++) { System.out.println("Cycle = " + i + "\n\n"); advanceonegen(currentgeneration, nextgeneration); printstate(nextgeneration); // swap current and next generations boolean[][] temp = nextgeneration; nextgeneration = currentgeneration; currentgeneration = temp;

readinitialgeneration() readinitialgeneration() part 2 // read the initial generation from the input // a dot means empty and a * means alive // any other characters are ignored // the border cells are all set to empty // the method assumes the array is square static void readinitialgeneration(boolean[][] w) { for (int i = 0; i < w.length; i++) for (int j = 0; j < w[i].length; j++) { char c = (char)console.in.readchar(); //skip illegal characters while (c!= '.' && c!= '*') c = (char)console.in.readchar(); if (c == '.') w[i][j] = EMPTY; else w[i][j] = ALIVE; //set border cells to be empty int border = w.length - 1; for (int i = 0; i < w.length; i++){ w[i][0] = w[0][i] = EMPTY; w[i][border] = w[border][i] = EMPTY; printstate() neighbors() // print a generation to the console static void printstate(boolean[][] w) { for (int i = 0; i < w.length; i++) { System.out.println(); for (int j = 0; j < w[i].length; j++) if (w[i][j] == ALIVE) System.out.print('X'); else System.out.print('.'); System.out.println(); // compute the number of alive neighbors of a cell static int neighbors(int row, int column, boolean[][] w) { int neighborcount = 0; for (int i = -1; i <= 1; i++) for (int j = -1; j <= 1; j++) if (w[row + i][column + j] == ALIVE) neighborcount = neighborcount + 1; if (w[row][column] == ALIVE) neighborcount--; return neighborcount;

advanceonegen() static void advanceonegen(boolean[][] wold, boolean[][] wnew) { int neighborcount; for (int i = 1; i < wold.length - 1; i++) for (int j = 1; j < wold[i].length - 1; j++) { neighborcount = neighbors(i, j, wold); if (neighborcount == 3) wnew[i][j] = ALIVE; else if (wold[i][j] == ALIVE && neighborcount == 2) wnew[i][j] = ALIVE; else wnew[i][j] = EMPTY; Cool Web Site Good description of the Game of Life Neat Java applet that runs simulations with different starting patterns Check it out at http://www.math.com/students/wonders/life/life.html static final boolean ALIVE = true; static final boolean EMPTY = false; Distributed Pair Programming Pair Programming has been shown to provide many benefits However, there is at least one major drawback You have to be collocated I am developing a tool to support distributed pair programming Supports pair programming from 2 separate locations Seeking Volunteers I am looking for some students who would like to try to use this tool You can use it on your homework assignments What do I want? Your honest feedback regarding your experience using the tool Did it work? How did distributed pairing compare to collocated pairing? What would you do to improve the tool?

Requirements You must have: A PC running Windows A sound card A high speed Internet connection (DSL, campus network, cable modem) Dial-up is probably not sufficient, although I don't know for sure You also need to have or set up: SSH (secure shell) AOL Instant Messenger Quiz 4 Covers topics in chapter 5 Single-dimensional and two-dimensional arrays Array length Array indexing Defining array references, allocating the array, and array initialization operator new default initialization initializer lists Quiz 4 Array assignment Passing arrays as parameters to methods Distinction between assignements to the array reference and array elements Common Errors with arrays indexing from 1 to length forgetting to allocate the array Big O notation what it means which orders are more efficient Write a single statement that declares an array of String, allocates the array, and assigns the array elements the values "one", "two", and "three". Write a single statement that declares and allocates a two dimensional array of int, with 10 rows and 5 columns.

Assume that you have a choice of two algorithms that you can use to sort the elements in an array. One of the algorithms performs in O(n log n) time, while the other performs in O(n 2 ) time. In general, which algorithm is more efficient? Write a method arraysum() that takes an array of int as a parameter and returns the sum of the array elements to the caller. Do not write a program write a method only. Assume a has the following definition: int a[][] = {{1,2,3, {4,5, {6,7,8,9; What is the value of the following expressions? a.length a[1].length a[1] a[1][1] a[1][2] a[2][0] What is printed by the following Java fragment? int firstarray[] = {1,2,3; int secondarray[] = {5,10,15,20,25; firstarray = secondarray; secondarray[0] = 15; System.out.println( firstarray[0] );

What is printed by the following Java program? class Q4Example1 { public static void main( String[] args ) { int a[] = {1,2; int b[] = {3,4; mystery( a, b ); System.out.println( "a[0] = " + a[0] ); System.out.println( "b[0] = " + b[0] ); static void mystery( int[] s, int[]t ) { s = t; System.out.println("s[0] = " + s[0] ); System.out.println("t[0] = " + t[0] ); The following Java program contains an error. Correct it. class Q4Example2 { public static void main( String[] args ) { int a[] = {1,2,3,4; mystery( a ); static void mystery( int[] a ) { for (int i = 0; i <= a.length; i++ ) System.out.println(a[i] + " "); What is printed by the following program? class Q4Example3 { public static void main( String[] args ) { String names[][] = {{"Brian", "Dave",{"Amy", "Karen",{"Sanjit", "Anne", "William"; mystery( names ); static void mystery( String[][] s ) { for (int i = 0; i < s.length; i++ ) { for (int j = 0; j < s[i].length; j++ ) System.out.print( s[i][j] + " " ); System.out.println(); What is printed by the following program? class Q4Example4 { public static void main( String[] args ) { int values[] = { 10, -5, 3, -2, -1, 12, -7 ; mystery( values ); for ( int i = 0; i < values.length; i++ ) System.out.print( values[i] + " " ); static void mystery( int[] s ) { for (int i = 0; i < s.length; i++ ) { if ( s[i] < 0 ) s[i] = -s[i];