Chapter 8 Multi-Dimensional Arrays

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

Chapter 7 Multidimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

Chapter 7 Multidimensional Arrays

Multidimensional Arrays. CSE 114, Computer Science 1 Stony Brook University

Introduction. Data in a table or a matrix can be represented using a two-dimensional array. For example:

Chapter 8 Multidimensional Arrays

15. Multidimensional Arrays

Computer Programming, I. Laboratory Manual. Experiment #9. Multi-Dimensional Arrays

CS115 Principles of Computer Science

Arrays. Eng. Mohammed Abdualal

Chapter 6. Arrays. Java Actually: A Comprehensive Primer in Programming

Object Oriented Programming. Java-Lecture 6 - Arrays

Chapter 6 Arrays, Part D 2d Arrays and the Arrays Class

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

Lecture #8-10 Arrays

CS1150 Principles of Computer Science Arrays

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

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

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

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

Spring 2010 Java Programming

Arrays and Lists CSC 121 Fall 2015 Howard Rosenthal

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 45 Obtained Marks:

Introduction to Algorithms and Data Structures

Chapter 6 Single-Dimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

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

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

Chapter 9 Introduction to Arrays. Fundamentals of Java

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Last Class. While loops Infinite loops Loop counters Iterations

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

Fundamentals of Programming Data Types & Methods

H212 Introduction to Software Systems Honors

Array. Lecture 12. Based on Slides of Dr. Norazah Yusof

Mid Term Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Total Marks: 50 Obtained Marks:

LAB 12: ARRAYS (ONE DIMINSION)

Over and Over Again GEEN163

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Array. Array Declaration:

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

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

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

Arrays. CS Feb 2008

Example: Computing prime numbers

Give one example where you might wish to use a three dimensional array

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

Web-CAT submission URL: CAT.woa/wa/assignments/eclipse

Programming with Java

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

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

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CAT.woa/wa/assignments/eclipse

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

CS 1063 Introduction to Computer Programming Midterm Exam 2 Section 1 Sample Exam

ITERATION WEEK 4: EXMAPLES IN CLASS

Declaring and ini,alizing 2D arrays

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

Question: Total Points: Score:

CS141 Programming Assignment #10

2.8. Decision Making: Equality and Relational Operators

Array basics. Readings: 7.1

Controls Structure for Repetition

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

Arrays. Chapter 7 Part 3 Multi-Dimensional Arrays

Learning objec-ves. Declaring and ini-alizing 2D arrays. Prin-ng 2D arrays. Using 2D arrays Decomposi-on of a solu-on into objects and methods

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

Module 7: Arrays (Single Dimensional)

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

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

An array is a collection of data that holds fixed number of values of same type. It is also known as a set. An array is a data type.

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

Object Oriented Programming. Java-Lecture 1

Java Coding 3. Over & over again!

Supplementary Test 1

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

CEN 414 Java Programming

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

CS1150 Principles of Computer Science Arrays

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Computer Science is...

Computer Science & Engineering 150A Problem Solving Using Computers

Question: Total Points: Score:

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

CS141 Programming Assignment #6

CS Computers & Programming I Review_01 Dr. H. Assadipour

Chapter 12: Arrays Think Java: How to Think Like a Computer Scientist by Allen B. Downey

CSE 1223: Introduction to Computer Programming in Java Chapter 1 Computer Basics

Arrays (Deitel chapter 7)

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Chapter 7 Single-Dimensional Arrays

Arrays, Part 3: Multidimensional arrays

Oct Decision Structures cont d

A Quick and Dirty Overview of Java and. Java Programming

Final Exam. COMP Summer I June 26, points

Top-down programming design

Lecture 5: Methods CS2301

Arrays and ArrayLists. David Greenstein Monta Vista High School

Transcription:

Chapter 8 Multi-Dimensional Arrays 1

1-Dimentional and 2-Dimentional Arrays In the previous chapter we used 1-dimensional arrays to model linear collections of elements. myarray: 6 4 1 9 7 3 2 8 Now think of each element in the array to be a 1-dimentional array. This gives us a matrix. 1 4 1 5 7 1 8 8 5 4 3 9 1 3 3 5 3 5 2 5 0 7 4 3 9 7 1 9 9 8 6 2 2

Two-dimensional Array Illustration matrix.length? 5 matrix[0].length? 5 array.length? 4 array[0].length? 3 3

Declare/Create Two-dimensional Arrays // Declare array reference variable datatype[][] refvar; //each [] represents one dimension // Create array and assign its reference to variable refvar = new datatype[10][10]; // Combine declaration and creation in one statement datatype[][] refvar = new datatype[10][10]; // Alternative syntax datatype refvar[][] = new datatype[10][10]; 4

Code Examples // Note that a matrix has rows and columns. First index // is for rows and second index for columns. double[][] distance; //declare matrix distance distance[0][0] = 295; //assign 295 to position [0,0] int[][] grades = new int[10][10]; //declare & create for (int i = 0; i < grades.length; i++) //rows for (int j = 0; j < grades[i].length; j++) //columns grades[i][j] = (int)(math.random() * 100); for (int i = 0; i < 10; i++) //process rows for (int j = 0; j < 10; j++) //process columns System.out.print (" " + grades[i][j]); System.out.println(); 5

Initialization Using Shorthand Notations You can also use an array initializer to declare, create and initialize 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; 6

Lengths of Two-dimensional Arrays int[][] x = new int[3][4]; 7

Lengths of Two-dimensional Arrays int[][] array = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ; array.length array[0].length array[1].length array[2].length array[3].length Runtime Error: array[4].length; //ArrayIndexOutOfBoundsException 8

Ragged Arrays Each row in a two-dimensional array is itself an array. So, the rows can have different lengths. Such an array is known as ragged array. For example, int[][] matrix = ; 1, 2, 3, 4, 5, 2, 3, 4, 5, 3, 4, 5, 4, 5, 5 matrix.length is 5 matrix[0].length is 5 matrix[1].length is 4 matrix[2].length is 3 matrix[3].length is 2 matrix[4].length is 1 9

Ragged Arrays, cont. 10

Processing Two-Dimensional Arrays See the examples in the text. 1. Initializing arrays with input values 2. Printing arrays 3. Summing all elements 4. Summing all elements by column 5. Which row has the largest sum 6. Finding the smallest index of the largest element 7. Random shuffling 11

Initializing arrays with input values java.util.scanner input = new Scanner(System.in); int[][] grades = new int[10][10]; System.out.println("Enter " + grades.length + " rows and " + grades[0].length + " columns: "); for (int row = 0; row < grades.length; row++) for (int column = 0; column < grades[row].length; column++) grades[row][column] = input.nextint(); 12

Initializing arrays with random values int[][] grades = new int[10][10]; for (int row = 0; row < grades.length; row++) for (int column = 0; column < gardes[row].length; column++) grades[row][column] = (int)(math.random() * 100); 13

Printing arrays for (int row = 0; row < grades.length; row++) for (int column = 0; column < grades[row].length; column++) System.out.print(grades[row][column] + " "); System.out.println(); //go to next row 14

Summing all elements int total = 0; for (int row = 0; row < grades.length; row++) for (int column = 0; column < grades[row].length; column++) total = total + grades[row][column]; 15

Summing elements by column for (int column = 0; column < matrix[0].length; column++) int total = 0; //reset for each column for (int row = 0; row < matrix.length; row++) total = total + matrix[row][column]; System.out.println("Sum for column " + column + " = " + total); 16

Random shuffling for (int i = 0; i < matrix.length; i++) for (int j = 0; j < matrix[i].length; j++) int i1 = (int)(math.random() * matrix.length); int j1 = (int)(math.random() * matrix[i].length); // Swap matrix[i][j] with matrix[i1][j1] int temp = matrix[i][j]; matrix[i][j] = matrix[i1][j1]; matrix[i1][j1] = temp; 17

Passing Two-Dimensional Arrays to Methods import java.util.scanner; public class PassTwoDimensionalArray public static void main(string[] args) int[][] table = getarray(); // call method getarray() // Display sum of elements System.out.println("\nSum of all elements is " + sum(table)); public static int[][] getarray() Scanner input = new Scanner(System.in);// Create a Scanner int[][] m = new int[3][4];// declare and create array m System.out.println("Enter " + m.length + " rows and " + m[0].length + " columns: "); //prompt for (int i = 0; i < m.length; i++) for (int j = 0; j < m[i].length; j++) m[i][j] = input.nextint(); return m; // code continues next slide 18

Passing Two-Dimensional Arrays to Methods // code continues from previous slide public static int sum(int[][] matrix) int total = 0; for (int row = 0; row < matrix.length; row++) for (int column = 0; column < matrix[row].length; column++) total = total + matrix[row][column]; return total; 19

Problem: Grading Multiple-Choice Test Students answer Objective: write a program that grades multiple-choice test. 20

Problem: Grading Multiple-Choice Test public class GradeExam public static void main(string args[]) // Students' answers to the questions char[][] answers = 'A', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D', 'D', 'B', 'A', 'B', 'C', 'A', 'E', 'E', 'A', 'D', 'E', 'D', 'D', 'A', 'C', 'B', 'E', 'E', 'A', 'D', 'C', 'B', 'A', 'E', 'D', 'C', 'E', 'E', 'A', 'D', 'A', 'B', 'D', 'C', 'C', 'D', 'E', 'E', 'A', 'D', 'B', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D', 'B', 'B', 'A', 'C', 'C', 'D', 'E', 'E', 'A', 'D', 'E', 'B', 'E', 'C', 'C', 'D', 'E', 'E', 'A', 'D'; // Key to the questions char[] keys = 'D','B','D','C','C','D','A','E','A','D'; // code continue next slide 21

Problem: Grading Multiple-Choice Test // code continues from previous slide // Grade all students for (int i = 0; i < answers.length; i++) // Grade one student int correctcount = 0; // reset count for each student for (int j = 0; j < answers[i].length; j++) if (answers[i][j] == keys[j]) correctcount++; System.out.println("Student " + i + "'s correct count is " + correctcount); 22

Multidimensional Arrays Occasionally, we need to represent n-dimensional data structures. In Java, you can create n-dimensional arrays for any integer n. The way to declare two-dimensional array variables and create two-dimensional arrays can be generalized to declare n-dimensional array variables and create n- dimensional arrays for n >= 3. 23

Problem: Calculating Total Scores Objective: write a program that calculates the total score for students in a class. Suppose the scores are stored in a three-dimensional array named scores. The first index in scores refers to a student, the second refers to an exam, and the third refers to the part of the exam. Suppose there are 7 students, 5 exams, and each exam has two parts--the multiple-choice part and the programming part. So, scores[i][j][0] represents the score on the multiple-choice part for the i s student on the j s exam. The program displays the total score for each student. 24

3-Dimensional Arrays double[][][] scores = 7.5, 20.5, 9.0, 22.5, 15, 33.5, 13, 21.5, 15, 2.5, 4.5, 21.5, 9.0, 22.5, 15, 34.5, 12, 20.5, 14, 9.5, 6.5, 30.5, 9.4, 10.5, 11, 33.5, 11, 23.5, 10, 2.5, 6.5, 23.5, 9.4, 32.5, 13, 34.5, 11, 20.5, 16, 7.5, 8.5, 26.5, 9.4, 52.5, 13, 36.5, 13, 24.5, 16, 2.5, 9.5, 20.5, 9.4, 42.5, 13, 31.5, 12, 20.5, 16, 6.5 ; Which student Which exam Multiple-choice or essay scores[ i ] [ j ] [ k ] 25

Problem: Calculating Total Scores public class TotalScore //Main method public static void main(string args[]) double[][][] scores = 7.5, 20.5, 9.0, 22.5, 15, 33.5, 13, 21.5, 15, 2.5, 4.5, 21.5, 9.0, 22.5, 15, 34.5, 12, 20.5, 14, 9.5, 6.5, 30.5, 9.4, 10.5, 11, 33.5, 11, 23.5, 10, 2.5, 6.5, 23.5, 9.4, 32.5, 13, 34.5, 11, 20.5, 16, 7.5, 8.5, 26.5, 9.4, 52.5, 13, 36.5, 13, 24.5, 16, 2.5, 9.5, 20.5, 9.4, 42.5, 13, 31.5, 12, 20.5, 16, 6.5, 1.5, 29.5, 6.4, 22.5, 14, 30.5, 10, 30.5, 16, 6.0 ; // Calculate and display total score for each student for (int i = 0; i < scores.length; i++) double totalscore = 0; for (int j = 0; j < scores[i].length; j++) for (int k = 0; k < scores[i][j].length; k++) totalscore = totalscore + scores[i][j][k]; System.out.println("Student " + i + "'s score is " + totalscore); See Listing 8.5 for another example - Weather data (day/hour/temperature or Humidity) 26

End of Chapter 8 27