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