Lecture 2. Two-Dimensional Arrays

Similar documents
Lecture 7. File Processing

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

ESC101 : Fundamental of Computing

Matrix Multiplication

Midterm Examination (MTA)

Matrix Multiplication

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

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

CSCE 110 PROGRAMMING FUNDAMENTALS. Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays

Programming with Java

Array. Array Declaration:

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

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

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

Introduction to Software Development (ISD) Week 3

CS141 Programming Assignment #10

Example: Monte Carlo Simulation 1

Nested Loops. A loop can be nested inside another loop.

Array. Prepared By - Rifat Shahriyar

Lesson 7. Reading and Writing a.k.a. Input and Output

Full file at

Parallelizing The Matrix Multiplication. 6/10/2013 LONI Parallel Programming Workshop

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

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

AP Computer Science A Unit 2. Exercises

Pace University. Fundamental Concepts of CS121 1

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

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

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

Module 16: Data Flow Analysis in Presence of Procedure Calls Lecture 32: Iteration. The Lecture Contains: Iteration Space.

CS141 Programming Assignment #6

How to swap values of two variables without tmp? However, this naive algorithm is biased. 1

Programmierpraktikum

Instructor: Eng.Omar Al-Nahal

Java Programs. System.out.println("Dollar to rupee converion,enter dollar:");

Exercise 4: Loops, Arrays and Files

Section 2.2 Your First Program in Java: Printing a Line of Text

Introduction to Computer Science Unit 2. Exercises

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

IST 297D Introduction to Application Programming Chapter 4 Problem Set. Name:

Section 2.2 Your First Program in Java: Printing a Line of Text

Experiment Objectives. 2. Preparation. 3. Tasks. 3.1 Task A: String to Integer Conversion

CS 177. Lists and Matrices. Week 8

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

COMPUTER SCIENCE. 4. Arrays. Section 1.4.

What did we talk about last time? Examples switch statements

QUIZ: loops. Write a program that prints the integers from -7 to 15 (inclusive) using: for loop while loop do...while loop

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

AP CS Unit 3: Control Structures Notes

Java Console Input/Output The Basics. CGS 3416 Spring 2018

CS141 Programming Assignment #5

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

Matrices. Jordi Cortadella Department of Computer Science

H212 Introduction to Software Systems Honors

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

Getting started with Java

BASIC INPUT/OUTPUT. Fundamentals of Computer Science

Oct Decision Structures cont d

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #16 Loops: Matrix Using Nested for Loop

Fundamentals of Programming Data Types & Methods

Java Arrays. What could go wrong here? Motivation. Array Definition 9/28/18. Mohammad Ghafari

Supplementary Test 1

Object Oriented Programming and Design in Java. Session 2 Instructor: Bert Huang

Problems with simple variables

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

Recitation: Loop Jul 7, 2008

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

Java Console Input/Output The Basics

Fall 2005 CS 11 Final exam Answers

Tutorial about Arrays

2. What are the two main components to the CPU and what do each of them do? 3. What is the difference between a compiler and an interpreter?

CPSC 319. Week 2 Java Basics. Xiaoyang Liu & Sorting Algorithms

SCHOOL OF COMPUTING, ENGINEERING AND MATHEMATICS SEMESTER 1 EXAMINATIONS 2015/2016 CI101 / CI177. Programming

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

Advanced Java Concept Unit 1. Mostly Review

Introduction to Computer Science Unit 2. Notes

Object Oriented Programming. Java-Lecture 6 - Arrays

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

System.out.printf("Please, enter the value of the base : \n"); base =input.nextint();

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

1. Find the output of following java program. class MainClass { public static void main (String arg[])

Lecture 5: Matrices. Dheeraj Kumar Singh 07CS1004 Teacher: Prof. Niloy Ganguly Department of Computer Science and Engineering IIT Kharagpur

Data Structures COE 312 ExamII Preparation Exercises

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

Computer Programming: C++

Introduction to Java & Fundamental Data Types

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

Object-Oriented Programming in Java

AP Computer Science Unit 1. Programs

Full file at

Final Exam. CSC 121 Fall Lecturer: Howard Rosenthal. Dec. 13, 2017

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

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Chapter 2: Basic Elements of Java

McGill University School of Computer Science COMP-202A Introduction to Computing 1

Warm up Exercise. What are the types and values of the following expressions: * (3 + 1) 3 / / 2.0 (int)1.0 / 2

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Java Coding 3. Over & over again!

Elementary Programming

Exercise (Revisited)

Transcription:

Lecture 2 Two-Dimensional Arrays 1

Lecture Content 1. 2-D Array Basics 2. Basic Operations on 2-D Array 3. Storing Matrices with Special Properties 4. Applications of 2-D Array 2

1. 2-D Array Basics An array that requires two indices to identify a particular element is called two-dimensional arrays (also called matrix). 2-D arrays are often used to represent tables of values consisting of information arranged in rows and columns. 3

1. 2-D Array Basics To identify a particular table element, we must specify two indices. By convention, the first index identifies the element s row and the second index identifies the element s column. In general, n-dimensional array is defined as an array of (n - 1)-dimensional arrays. That is, 2-D array is an array of 1-D arrays, 3-D array is an array of 2-D arrays, and so on. 4

1. 2-D Array Basics The figure shown below illustrates a twodimensional array a that contains three rows and four columns (i.e., a three-by-four array). In general, an array with m rows and n columns is called an m-by-n array. 5

1. 2-D Array Basics Every element of array a in the figure above is identified by an array-access expression of the form a[i][j]; a is the name of the array, and i and j are the indices that uniquely identify each element in array a by row and column number. 6

1. 2-D Array Basics A 2-D array is declared as follows. int[][] a; // a = null or int[][] a = {{1, 2, 3}, {4, 5, 6}}; // 2-by-3 array of integers or int a[][] = {{1, 2, 3}, {4, 5, 6}}; 7

1. 2-D Array Basics Array rows can have different columns as follows. int[][] b = {{1, 2}, {3, 4, 5}}; The compiler counts the number of nested array initializers (represented by sets of braces within the outer braces) in the array declaration to determine the number of rows in array b. The compiler counts the initializer values in the nested array initializer for a row to determine the number of columns in that row. 8

Lecture Content 1. 2-D Array Basics 2. Basic Operations on 2-D Array 3. Storing Matrices with Special Properties 4. Applications of 2-D Array 9

2. Basic Operations on 2-D Array - input a matrix - output a matrix - add two matrices - multiply two matrices - permute a matrix - find min or max element of a matrix 10

Input a Matrix int a[][]; System.out.print("Enter #rows:"); M = in.nextint(); System.out.print( "Enter #columns:"); N = in.nextint(); a = new int[m][n]; 11

Input a Matrix public static void inputmatrix( int a[][], int M, int N) { Scanner in = new Scanner(System.in); System.out.println( "Enter elements"); 12

Input a Matrix for (int i = 0; i < M; i++) { // scan rows for (int j = 0; j < N; j++) { // scan columns System.out.print( "Element (" + i + ", " + j + ") = "); a[i][j] = in.nextint(); } } } // end of inputmatrix() 13

Output a Matrix public static void outputmatrix( int a[][]) { // output elements of a 2-D array int i = 0, j = 0; // loop through array's rows for (i = 0; i < a.length; i++) { // loop through columns of current row 14

Output a Matrix for (j = 0; j < a[i].length; j++) System.out.printf( "%d ", a[i][j]); // start new line of output System.out.println(); } // end outer for } // end method outputmatrix() 15

Matrix Addition C m n = A m n + B m n C ij = A ij + B ij, 0 i < m, 0 j < n 16

Matrix Addition public static void add(int a[][], int b[][], int c[][]) { int i = 0, j = 0; for (i = 0; i < a.length; i++) for (j = 0; j < a[i].length; j++) c[i][j] = a[i][j] + b[i][j]; } // end method add() 17

Example of Matrix Addition Values in matrix A 1 2 3 4 Values in matrix B 5 6 2 1 C = A + B 6 8 5 5 18

Matrix Multiplication. 19

Matrix Multiplication public static void multiply(int a[][], int b[][], int c[][]) { int i = 0, j = 0, k = 0; for (i = 0; i < a.length; i++) { // m rows for (j = 0; j < b[i].length; j++) { // n columns c[i][j] = 0; 20

Matrix Multiplication for (k = 0; k < a[i].length; k++) // p products c[i][j] += a[i][k] * b[k][j]; } } } // end method multiply() 21

Example of Matrix Multiplication Values in matrix A 1 2 3 4 5 6 Values in matrix B 5 6 2 1 3 4 C = A x B 18 20 48 53 22

Matrix Permutation public static void permute(int a[][], int pa[][]) { int i = 0, j = 0; for (i = 0; i < a.length; i++) { for (j = 0; j < a[i].length; j++) { pa[j][i] = a[i][j]; } } } // end method permute() 23

Example of Matrix Permutation Values in matrix A 1 2 3 4 5 6 Permuted A is pa 1 4 2 5 3 6 24

Find Minimum Element of Matrix public static int minmatrix(int a[][]) { int i = 0, j = 0, min = a[0][0]; for (i = 0; i < a.length; i++) { for (j = 0; j < a[i].length; j++) { if (a[i][j] < min) min = a[i][j]; } } return min; } // end method minmatrix() 25

Find Maximum Element of Matrix public static int maxmatrix(int a[][]) { int i = 0, j = 0, max = a[0][0]; for (i = 0; i < a.length; i++) { for (j = 0; j < a[i].length; j++) { if (a[i][j] > max) max = a[i][j]; } } return max; } // end method maxmatrix() 26

Lecture Content 1. 2-D Array Basics 2. Basic Operations on 2-D Array 3. Storing Matrices with Special Properties 4. Applications of 2-D Array 27

Store Elements of 2D Array to 1D Array Values in 2D array a[m][n] by row are Values in 1D array b[m * n] are 28

Store Elements of 2D Array to 1D Array public static void store2dto1d( int a[][], int b[]) { int i = 0, j = 0; for (i = 0; i < a.length; i++) { for (j = 0; j < a[i].length; j++) b[i*n + j] = a[i][j]; } } 29

Store Elements of 1D Array to 2D Array Values in 1D array b[m * n] are Values in 2D array a[m][n] by row are 30

Store Elements of 1D Array to 2D Array public static void store1dto2d( int b[], int a[][]) { int i = 0, j = 0; for (i = 0; i < a.length; i++) { for (j = 0; j < a[i].length; j++) a[i][j] = b[i*n + j]; } } 31

Store Elements of 1D Array to 2D Array public static void store1dto2d( int b[], int a[][]) { for (int k = 0; k < m*n; k++) a[k / n][k % n] = b[k]; } 32

Triangular Matrices An n n lower-triangular matrix a[1..n][1..n] is one in which the non-zero elements are all found on or below the main diagonal, in lower triangle; all elements above the main diagonal are zero. 33

Triangular Matrices We need to store 1 + 2 + 3 = 6 elements (i.e., n(n + 1)/2). An element a ij property i < j. above the main diagonal has the An element a ij below or on the main diagonal has the property i j. a ij is stored in 1D array at b[i(i - 1) / 2 + j] 34

Triangular Matrices public static void store2dto1d( int a[][], int b[]) { int i = 0, j = 0; for (i = 1; i < a.length; i++) { for (j = 1; j < a[i].length; j++) b[i * (i - 1) / 2 + j] = a[i][j]; } } 35

Triangular Matrices public static void store1dto2d( int b[], int a[][]) { int i = 0, j = 0; for (i = 1; i < a.length; i++) { for (j = 1; j < a[i].length; j++) if (i < j) a[i][j] = 0; else a[i][j] = b[i * (i - 1) / 2 + j]; } } 36

Triangular Matrices Values in 2D array a[n+1][n+1] by row are Values in 1D array b[n*(n+1)/2] are 37

Triangular Matrices Values in 1D array b[n*(n+1)/2] are Values in 2D array a[n+1][n+1] by row are 38

Symmetric Matrix A symmetric matrix a[1..n][1..n] is one in which a ij = a ji. We need to store 1 + 2 + 3 = 6 elements (i.e., n(n + 1)/2). a ij is stored in 1D array at b[i(i - 1) / 2 + j]. 39

Symmetric Matrix An element a ij below or on the main diagonal (i.e., i j) is retrieved from b[i(i - 1) / 2 + j]. An element a ij above the main diagonal (i.e., i < j) is retrieved from b[j(j - 1) / 2 + i]. 40

Symmetric Matrix public static void store2dto1d( int a[][], int b[]) { int i = 0, j = 0; for (i = 1; i < a.length; i++) { for (j = 1; j < a[i].length; j++) b[i * (i - 1) / 2 + j] = a[i][j]; } } 41

Symmetric Matrix public static void store1dto2d( int b[], int a[][]) { int i = 0, j = 0; for (i = 1; i < a.length; i++) { for (j = 1; j < a[i].length; j++) if (i >= j) a[i][j] = b[i * (i - 1) / 2 + j]; else a[i][j] = b[j * (j - 1) / 2 + i]; } } 42

Lecture Content 1. 2-D Array Basics 2. Basic Operations on 2-D Array 3. Storing Matrices with Special Properties 4. Applications of 2-D Array 43

Digital Image Processing Application Original grayscale Lena image sized 512 512 pixels 44

Read Image Data Stored in File public static void readimagefile(string fn, int I[][]) throws IOException { // Read original image data into I[][] int i = 0, j = 0; System.out.println( "Reading image file " + fn); FileInputStream fin = new FileInputStream(fn); for (i = 0; i < H; i++) { // scan image height (rows) 45

Read Image Data Stored in File for (j = 0; j < W; j++) { // scan image width (columns) // read one byte of image data I[i][j] = fin.read(); } } fin.close(); } // end readimagefile() 46

Read Image Data Stored in File import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.ioexception; public class imageapp { final static int H = 512; // image height final static int W = 512; // image width... } // H and W are class data values // H and W are constant data values 47

Display Image Data on Screen public static void displayimage(int I[][]) { // display image data in I[][] onto screen int i = 0, j = 0; for (i = 0; i < H; i++) { // loop through image's rows // loop through image's columns for (j = 0; j < W; j++) System.out.printf("%4d", I[i][j]); // start new line of output System.out.println(); } // end outer for } // end displayimage() 48

Write Image Data to File public static void saveimage(int I[][], String fn) { // save processed image data in I[][] // to image file int i = 0, j = 0; System.out.println( "Saving image data " + fn); try { FileOutputStream fout = new FileOutputStream(fn, false); 49

Write Image Data to File for (i = 0; i < H; i++) { // scan image height (rows) for (j = 0; j < W; j++) { // scan image width (columns) } } // write one byte of image data to file fout.write(i[i][j]); 50

Write Image Data to File fout.close(); } // end try catch (IOException ioe) { } } // end saveimage() 51

Image Permutation public static void permuteimage( int I[][], int PI[][]) { // permute image I to be // permuted image PI int i = 0, j = 0; 52

Image Permutation for (i = 0; i < H; i++) { // scan image height (rows) for (j = 0; j < W; j++) { // scan image width (columns) PI[j][i] = I[i][j]; } } } // end permuteimage() 53

Permuted Image Permuted Lena (Horizontal flip, Left Rotation 90 o ) 54

Make Image Brighter Original Lena image Brighter image 55

Make Image Brighter public static void brighterimage( int I[][], int BI[][]) { // make image I to be brighter image BI int i = 0, j = 0; for (i = 0; i < H; i++) { // scan image height (rows) 56

Make Image Brighter for (j = 0; j < W; j++) { // scan image width (columns) if (I[i][j] < 215) BI[i][j] = I[i][j] + 40; else BI[i][j] = 255; } } } // end brighterimage() 57

Make Image Darker Original Lena image Darker image 58

Make Image Darker public static void darkerimage( int I[][], int DI[][]) { // make image I to be darker image DI int i = 0, j = 0, min = 0; for (i = 0; i < H; i++) { // scan image height (rows) 59

Make Image Darker for (j = 0; j < W; j++) { // scan image width (columns) if (I[i][j] > 40) DI[i][j] = I[i][j] - 40; else DI[i][j] = 0; } } } // end darkerimage() 60

Convert Grayscale Image to Binary Image Original Lena image Binary image 61

Convert Grayscale Image to Binary Image public static void BWImage(int I[][], int BWI[][]) { // make image I to be binary image // BWI int i = 0, j = 0; for (i = 0; i < H; i++) { // scan image height (rows) 62

Convert Grayscale Image to Binary Image for (j = 0; j < W; j++) { // scan image width (columns) if (I[i][j] <= 127) // black color BWI[i][j] = 0; else // white color BWI[i][j] = 255; } } } // end BWImage() 63

Input/Output from/to Keyboard/Screen import java.util.scanner; class inputoutput { public static void main( String[] args) { Scanner in = new Scanner(System.in); 64

Input/Output from/to Keyboard/Screen System.out.print( "Enter an integer number: "); int x = in.nextint(); System.out.printf( "The entered integer is %d\n", x); 65

Input/Output from/to Keyboard/Screen System.out.print( "Enter a real number (float): "); float y = in.nextfloat(); System.out.printf( "The entered real number (float) is %.2f\n", y); 66

Input/Output from/to Keyboard/Screen System.out.print( "Enter a real number (double): "); double z = in.nextdouble(); System.out.printf( "The entered real number is %.2f\n", z); 67

Input/Output from/to Keyboard/Screen System.out.print( "Enter a character: "); String str = in.next(); char chr = str.charat(0); System.out.printf("The entered letter is %c\n", chr); 68

Input/Output from/to Keyboard/Screen System.out.print( "Enter a word (string without spaces): "); String w = in.next(); System.out.printf( "The entered word is %s\n", w); 69

Input/Output from/to Keyboard/Screen System.out.print( "Enter a string (with spaces): "); in.nextline(); // clear '\n' in buffer String strg = in.nextline(); System.out.printf( "The entered string is %s\n", strg); } // end main() } // end class inputoutput 70

Exercises I. Write complete Java programs to perform the following basic operations on 2-D array (i.e., matrix). 1. Input an m-by-n matrix a. 2. Output an m-by-n matrix a. 3. Add two matrices a m n and b p q to obtain matrix s. 4. Multiply two matrices a m n and b p q to obtain matrix M. 5. Permute a matrix a m n to obtain matrix pa n m. 6. Find the minimum element of an m-by-n matrix a. 7. Find the maximum element of an m-by-n matrix a. 71

Exercises II. Use the formulas presented in the lecture notes to write complete Java programs to perform the following tasks. 1. Store the elements of a 2D array a[1..m][1..n] to a 1D array b[1..m n] and vice versa. 2. Store the elements of an n n lower-triangular matrix a[1..n][1..n] to a 1D array b[1..n(n + 1)/2] and vice versa. 3. Store the elements of an n n symmetric matrix a[1..n][1..n] to a 1D array b[1..n(n + 1)/2] and vice versa. 72

References 1. Noel Kalicharan. 2008. Advanced Programming in Java. CreateSpace Press. ISBN: 1438283016. 2. Y. Daniel Liang. 2014. Introduction to Java Programming, Comprehensive Version. 10th Ed. Prentice Hall. ISBN: 0133761312. http://www.cs.armstrong.edu/liang/ 3. Paul Deitel, Harvey Deitel. 2014. Java How to Program, Early Objects. 10 th Ed. Prentice Hall. ISBN: 0133807800. http://www.deitel.com 73

References 4. Water Savitch, Kenrick Mock. 2015. Absolute Java. 6 th Ed. Pearson. ISBN: 0134041674. http://www.pearsonhighered.com/savitch 74