TAILIEUCHUNG - Lecture An introduction to computer science using java (2nd Edition): Chapter 9 - S.N. Kamin, D. Mickunas, E. Reingold
Chapter 9 - Nested loops and two-dimensional arrays. In this chapter we will: show how nested loops are useful, introduce two-dimensional arrays, describe the use of two-dimensional arrays to represent grids of information, show how computer graphics are generated using pixels. | Chapter 9 Nested Loops and Two-Dimensional Arrays Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by . Kamin, D. Mickunas, E. Reingold Chapter Preview In this chapter we will: show how nested loops are useful introduce two-dimensional arrays describe the use of two-dimensional arrays to represent grids of information show how computer graphics are generated using pixels Nested for Loops Nested loops frequently used to process two-dimensional arrays Often body of inner loop is where the main computation is done Example: for (i = 0; i < m; I++) { before inner loop for (j = 0; j < n; j++) body of inner loop after inner loop }; Dependent for Loops Sometimes the extent of the inner nested loop will depend on the index value of the outer loop Example: for (i = 0; i < 3; i++) { (“i= “; + i + “: j = “); for (j = 0; j <= i; j++) { (“ “ + j); } } Nested Loop Contained in Other Statements for (int i = 1; i <= 10; i++) { if (i % 2 == 0) // i even for (int j = 1; j <= i/2; j++) (“*”); else // i odd for (int k = 1; k <= 5 – i/2; k++) (“#”); (); } Output ##### * #### ** ### *** ## **** # ***** Two-Dimensional Arrays Declaration similar to one dimensional arrays Need to specify both the number of rows and columns during allocation Example: final int COLS = 6, ROWS = 5; double[][] energyTable = new double[ROWS][COLS] Computing Row Totals double [] yearTotals = new double[ROWS]; for (y = 0; y < ROWS; y++) { // compute total for year y yearTotals[y] = ; for (s =0; s < COLS; s++) yearTotals[y] = yearTotals[y] + energyTotal[y][s]; } Populating energyTable int y, s; // reads 30 numbers needed to fill // energyTable one row at a time for (y = 0; y < ROWS; y++) for (s = 0; s < COLS; s++) energyTable[y][s] = (); Initializing Two-Dimensional Arrays double[][] energyTable = { {, , , , , }, {, , , , , }, {, , , , , }, {,
đang nạp các trang xem trước