Presentation is loading. Please wait.

Presentation is loading. Please wait.

multi-dimensional arrays

Similar presentations


Presentation on theme: "multi-dimensional arrays"— Presentation transcript:

1 multi-dimensional arrays

2 Two-dimensional arrays are used to represent a table of data.
1. declaration Two-dimensional arrays are used to represent a table of data. The following statement declares a tic-tac-toe board with 3 rows and 3 columns: char tictac[3][3]; The total number of elements in such array is 3 x 3 = 9 elements. Col 0 Col 1 Col 2 Row 0 X O Row 1 Row 2 Dr. Soha S. Zaghloul 2

3 The table below shows how to refer to each of the elements of tic-tac:
2. Referencing The table below shows how to refer to each of the elements of tic-tac: In a two-dimensional array, each element is referenced by two subscripts: the number of the row the number of the column The number of the row is used first. For example, tictac [2][0] refers to the element in row 2, and column 0. This is shown in the figure. Compare this with the element tic-tac[0][2] Col 0 Col 1 Col 2 Row 0 0,0 0,1 0,2 Row 1 1,0 1,1 1,2 Row 2 2,0 2,1 2,2 Dr. Soha S. Zaghloul 3

4 Values are grouped by rows. For example:
3. initialization Values are grouped by rows. For example: char tic-tac[3][3] = { {‘ ‘, ‘ ‘, ‘ ‘}, {‘ ‘, ‘ ‘, ‘ ‘}, {‘ ‘, ‘ ‘, ‘ ‘} }; The blue braces represent the first row, the green ones correspond to the second, and the red one represent the third row. Two-dimensional arrays may also be initialized using a nested loop as follows: char tictac[3][3]; int row, col; for (row = 0; row < 3; row++) for (col = 0; col < 3; col++) tictac[row][col] = ‘ ‘; Dr. Soha S. Zaghloul 4

5 The following code displays the contents of the array tictac:
4. Displaying an array The following code displays the contents of the array tictac: char tictac[3][3]; int row, col; for (row = 0; row < 3; row++) for (col = 0; col < 3; col++) printf (“ tictac[%d][%d] = %c”, row, col, tictac[row][col]); Dr. Soha S. Zaghloul 5

6 5. Arrays with several dimensions
In the C language, we may have several dimensions of the array. Declaration is performed in the same way as two- dimensional. However, we’ll have a third number in the declaration. Example: int enroll[100][5][4]; Initialization will be performed in a nested loop of three dimensions: int enroll[100][5][4]; int i, j, k; for (i=0; i<100; i++) for (j=0; j<5; j++) for (k=0; k< 4; k++) enroll[i][j][k] = 0; Dr. Soha S. Zaghloul 6

7 6. Arrays with several dimensions - example
An example of a 3-dimensional array may be that representing a calendar: #define month 12 #define week 5 #define day 7 char year[month][week][day]; Therefore, the element year[10][3][5] represents month 11 (November), the fourth week in the month, and the sixth day in the week (Friday if we assumed Sun is the first day of the week). Dr. Soha S. Zaghloul 7


Download ppt "multi-dimensional arrays"

Similar presentations


Ads by Google