Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

Arrays. INTRODUCTION TO ARRAYS Just as with loops and conditions, arrays are a common programming construct and an important concept Arrays can be found.
Microsoft Visual Basic 2010: Reloaded Fourth Edition
Arrays. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
ECE122 L14: Two Dimensional Arrays March 27, 2007 ECE 122 Engineering Problem Solving with Java Lecture 14 Two Dimensional Arrays.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
C++ for Engineers and Scientists Third Edition
Chapter 9 Introduction to Arrays
© The McGraw-Hill Companies, 2006 Chapter 16 Two-dimensional arrays.
11 Chapter 8 ARRAYS Continued. 22 MULTI-DIMENSIONAL ARRAYS A one-dimensional array is useful for storing/processing a list of values. For example: –The.
Java Unit 9: Arrays Declaring and Processing Arrays.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
CPS120: Introduction to Computer Science Arrays. Arrays: A Definition A list of variables accessed using a single identifier May be of any data type Can.
Introducing Arrays We will often need to store collections of information –a list of names to sort –a list of values to compute averages, standard deviation,
Arrays (Part 1) Computer Science Erwin High School Fall 2014.
A First Book of ANSI C Fourth Edition
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Chapter 9: Arrays J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second Edition.
2D-Arrays Quratulain. Learning Objectives Two-dimensional arrays Declaration Initialization Applications.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
DATA STRUCTURES LAB 1 TA: Nouf Al-harbi
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
DT249-Information Systems Research Practice Programming Revision Lecture 2 Lecturer: Patrick Browne.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Advanced Computer Science Lesson 4: Reviewing Loops and Arrays Reading User Input.
CPS120: Introduction to Computer Science Lecture 15 Arrays.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Chapter 8: Arrays Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 8 Arrays.
The Math Class Methods Utilizing the Important Math Operations of Java!
Introducing Arrays We will often need to store collections of information –a list of names to sort –a list of values to compute averages, standard deviation,
1 Arrays of Arrays An array can represent a collection of any type of object - including other arrays! The world is filled with examples Monthly magazine:
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Student Grades Application Introducing Two-Dimensional Arrays and RadioButton.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays.
Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 Khalid Siddiqui.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
More on Logic Today we look at the for loop and then put all of this together to look at some more complex forms of logic that a program will need The.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
COMP 110: Spring Announcements Lab 7 was due today Binary Expression Assignment due Friday.
ARRAYS Multidimensional realities Image courtesy of
Chapter 9 Introduction to Arrays Fundamentals of Java.
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Lecture 18: Nested Loops and Two-Dimensional Arrays
Lesson 8: Introduction To Arrays
EGR 2261 Unit 10 Two-dimensional Arrays
Two-Dimensional Arrays
Lecture 13: Two-Dimensional Arrays
Building Java Programs
Presentation transcript:

Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!

Two-D Arrays Are Tables Arrays may have multiple dimensions. Two-dimensional arrays can be visualized as tables with rows and columns. A two dimensional array is really an “array of arrays” where each element of a one-dimensional array contains another array.

Declaring & Instantiating Two-D Arrays A good name for a two-dimensional array variable is table. Here is how you would declare and instantiate a two-dimensional array of integers with 4 rows and 5 columns: int [ ] [ ] table = new int [4] [5];

Conceptualizing Two-D Arrays The variable table references an array of four elements. Each of these elements in turn references an array of five integers … table is really an array of arrays. int [ ] [ ] table = new int [4][5];

Conceptualizing Two-D Arrays More specifically, table is an array of four memory locations and in each memory location of that array there is an array that has five memory locations. So table[0] refers to the first row of the 2D array and table[1] refers to the second row, table[2] refers to the third row and table[3] refers to the fourth row. Using the code table[2][3] allows us to work with the memory location in the third row and fourth column named row 2 column 3.

Conceptualizing Two-D Arrays A table of numbers, for instance, can be implemented as a two-dimensional array. The figure shows a two-dimensional array with four rows and five columns that contains some numbers.

Examples of Two-D Array Declarations int [ ] [ ] nums = new int [4][5]; double[ ] [ ] averages = new double [4][5]; String [ ] [ ] names = new String [4][5]; Student [ ] [ ] seatingChart = new Student [4][5]; Employee [ ] [ ] employees = new Employee [4][5];

Accessing an Element of a Two-D Array Suppose we name the array table ; then to indicate an element in table, we specify its row and column position, remembering that index values start at 0: x = table[2][3]; // Set x to 23, the value in (row 2, column 3)

Storing Values in a Two-D Array Here is the declaration & construction for a new table: int [ ] [ ] table = new int [3][4]; Let’s say we want these values stored in the array: Then the code that will do that is ….

Storing Int Values in a Two-D Array int [ ] [ ] table = new int [3][4]; The code to store these values could be: for (int row = 0; row < 3; row++) { for (int col = 0; col < 4; col++) { table[ row ] [ col ] = row + col ; } row and col are much better names for the loop control variables as they add readability to the code … helping us remember which loop controls the row we are on and which controls which column we are on.

Using table.length & table[row].length int [ ] [ ] table = new int [3][4]; Since the array might be resized later, then the code to store these values should be: for (int row = 0; row < table.length; row++) for (int col = 0; col < table[row].length; col++) table[ row ] [ col ] = row + col; table.length is the number of rows table[ row ].length is the number of columns Since we only have one line of code in the inner loop we do away with curly braces for that loop and we don’t have them for the outer loop because a loop is considered to be one statement.

Printing the values of a Two-D Array for (int row = 0; row < table.length; row ++) { for (int col = 0; col < table[row].length; col ++) { System.out.print(table[ row ] [ col ] + “ ”); } System.out.println(); // outside inner loop } Just like in the NestedLoopMania program, the System.out.println statement outside the inner loop starts a new row of output.

Summing Elements of a Two-D Arrays If we wanted to sum the values in the array, we could use: int sum = 0; for (int row = 0; row < table.length; row++) { for (int col = 0; col < table[ row ].length; col++) { sum += table[ row ] [ col ]; }

Alternate Declarations and Construction Just like one-dimensional arrays, two-dimensional arrays may be declared and instantiating in two different lines: // The following line of code can be broken down into: int [][] table = new int [4][5]; int [ ][ ] table; // Declaring a 2D array reference variable table = new int [4][5]; // Instantiating a 2D array for table It makes more sense to do it all in one line.

Storing Doubles in a 2D Array double [ ] [ ] table = new double [7][6]; The following code stores random floating point values between 0 inclusive and 1.0 exlcusive in the 2D array: for (int row = 0; row < table.length; row++) for (int col = 0; col < table[row].length; col++) table[ row ] [ col ] = Math.random();

Storing Strings in a 2D Array String [ ] [ ] table = new String [10][10]; Scanner reader = new Scanner (System.in); The following code stores string values from the keyboard into the 2D array: for (int row = 0; row < table.length; row++) for (int col = 0; col < table[row].length; col++) table[ row ] [ col ] = reader.nextLine();

Storing Employees in a 2D Array Employee [ ] [ ] table = new Employee [5][10]; Scanner reader = new Scanner (System.in); The following code stores Employee values from the keyboard into the 2D array: for (int row = 0; row < table.length; row++) for (int col = 0; col < table[row].length; col++) { System.out.print(“Enter the employee name: ”); String name = reader.nextLine(); System.out.print(“Enter the employee gender: ”); String gender = reader.nextLine(); table[ row ] [ col ] = new Employee (name, gender); }

Row-Sum Example We can compute the sum of each row separately and place each sum in a one- dimensional array named rowSum. Here is how we can visualize our data structures: –A one dimensional array called rowSum to store the sum of each row in table. –A two-dimensional array called table to hold all the values for the program The code to accomplish this is on the next slide.

Row-Sum Example Code The code for calculating the sum of each row and storing it in the array rowSum. The size of rowSum should be the number of rows in the 2D array table. int [ ] rowSum = new int [table.length]; for (int row = 0; row < table.length; row++) { for (int col = 0; col < table[ row ].length; col++) { rowSum[ row ] += table[ row ] [ col ]; }

Two-D Array Initializer Lists Declaring and instantiating a two-dimensional array of integers using an initializer list: int[][] table = { { 0, 1, 2, 3, 4}, // row 0 {10, 11, 12, 13, 14}, // row 1 {20, 21, 22, 23, 24}, // row 2 {30, 31, 32, 33, 34} // row 3 }; Notice there is no comma after the last row. The number of inner lists determines the number of rows. So the number of values in each list determines the number of columns.

Ragged Arrays Ragged arrays are rows of a two-dimensional array that are not all the same length. We mention them in passing. You do not need to know them for the AP Exam. int[ ][ ] table; table = new int[4][ ];// table has 4 rows // no columns specified table[0] = new int[6];// row 0 has 6 elements table[1] = new int[10];// row 1 has 10 elements table[2] = new int[100];// row 2 has 100 elements table[3] = new int[1];// row 3 has 1 element

10.10 The TicTacToe Program UML Square class defines a Square object TicTacToeBoard class defines and manages a TicTacToeBoard TicTacToeGUI class an applet driver program that displays and manges the TicTacToe Game 9 1 In the TicTacToe programming project we will divide the responisibility of different parts of the program between three files: 1)The Square class is an all purpose class that can be used with numerous board games. 2)The TicTacToeBoard class manages the functions of a TicTacToe game and implements it as a two-dimensional array of Square objects. 3)The TicTacToeGUI class is a view file that sets up the GUI and instantiates the TicTacToeBoard and processes the moves by the players.

10.10 Diagram of the TicTacToe Program “-” false “-” false “-” false “-” false “-” false “-” false “-” false “-” false “-” false Each memory location of the two-dimensional array contains a Square object that has two instance values …. a String which is initially set to “-” and a boolean which is set to “false”. When a player chooses a location on the board, then the String value is changed to either an “X” or “O” and the boolean value is changed to “true” to indicate the location has been chosen.

10.10 Diagram of the TicTacToe Program “X” true “O” true “X” true “-” false “X” true “O” true “X” true “O” true “O” true If the Xs win the state of the board might be this.

10.10 Diagram of the TicTacToe Program “X” true “O” true “X” true “X” true “X” true “O” true “O” true “X” true “O” true If the game is a tie then the state of the board might be this.

The Software Layers of TicTacToe 9 1 The Square class makes changes to Square objects and returns values when needed to the TicTacToeBoard class where the Square class methods are called. The TicTacToeBoard class constructs and mangaes a two- dimensional array of Square objects. The methods of this class are called by the driver class TicTacToeGUI. However, the methods in this class call methods of the Square class to do their work. The TicTacToeGUI driver class manages the view and interactions of the program with the user and controls the game by calling methods of the TicTacToeBoard class based on the input received from the GUI. Square Class TicTacToeBoard Class TicTacToeGUI Class This is an example of software layering, where different files have different responsibilities but each class only has access to the class immediately below it.

The Software Layers of TicTacToe Square model class TicTacToeBoard model class TicTacToeGUI driver class In software layering, you usually only want a class to have access to the methods in the class below it. In large software systems, this is desirable and adds an efficient level of organization that allows for testing and troubleshooting.

The Square Model Class Methods The Square class has two instance variables the String value and the boolean chosen. The methods that will be called the most are: the Square(String v, boolean b) initializing constructor the getValue() accessor method the getChosen() accessor method the setValue(String v) mutator method the setChosen(boolean b) mutator method These methods will all be called only by the TicTacToeBoard class methods in our TicTacToe program. The TicTacToeBoard class is the software layer immediately above the Square class.

The TicTacToeBoard Model Class Methods The TicTacToeBoard class has only one instance variable the two- dimensional array of Square objects named board. The most important methods that will be called are: the TicTacToeBoard () default constructor that constructs the board and fills it with Square objects having values of “-” and false. the String getBoardSquareValue(int row, int col) accessor method that gets the String value stored in a Square object located at position (row, col) and returns the String value. It gets the String value by calling the Square class accessor method getValue(). the boolean getBoardSquareChosen(int row, int col) accessor method that gets the boolean value stored in a Square object located at position (row, col) and returns the boolean value. It gets the boolean value by calling the Square class accessor method getChosen().

The TicTacToeBoard Model Class Methods the boolean setBoardSquareValue(int row, int col, String letter) mutator method that checks the board’s Square chosen boolean value at (row, col) to see if that Square has been chosen yet. If it has not then the method changes the Square’s String value from “-” to “X” or “O”, and its boolean chosen value from false to true. If the method changes the Square’s values then it returns true. If it doesn’t the method returns false. If it changes the Square’s values, it does so by calling the Square class mutator methods setValue() and setChosen(). the isFull() method checks to see if all of the “-” String values have been changed to “X” or “O”. This method will use a nested loop to check every Square object. If it finds even one “-” value anywhere in the two-dimensional array, then it returns false. If none are found, then it returns true. It does so by calling the Square class accessor method getValue().

The TicTacToeBoard Model Class Methods the void reset() method resets all the Square objects in the two-dimensional array to “-” and false. It does so by calling the Square class mutator methods setValue() and setChosen(). the boolean won(String letter) method checks to see if there are three “X”s or three “O”s in any row, column, or diagonal. This method takes the String value passed to it and immediately concatentates three of the letters together to make either “XXX” or “OOO”. It then retrieves all of the String values from the Square objects in a row, column, or diagonal to see if there is a matching three letters. If there is, the “X”s or “O”s have won and the method returns true. If there is no match the method returns false. It does so by calling the Square class accessor method getValue() for every board Square.

The TicTacToeBoard Model Class Methods These methods will all be called only by the TicTacToeGUI driver class methods in our TicTacToe program. The TicTacToeGUI driver class is the software layer immediately above the TicTacToeBoard class. Square model class TicTacToeBoard model class TicTacToeGUI driver class