محاضرة 6
2D Arrays
تعريف واستخدام المصفوفات ذات البعدين (صفوف وأعمدة)
ملخص المحاضرة
📜 Lecture 6: 2D Arrays
This lecture expands on arrays, introducing 2D (two-dimensional) arrays, also known as matrices.
Key Concepts
-
2D Array: An "array of arrays". Think of it as a grid or a table with rows and columns.
-
Syntax:
int a[ROWS][COLUMNS];.int a[3][4];declares a 2D array with 3 rows and 4 columns.
-
Initialization:
- Method 1 (Flat):
int a[3][4] = {1, 2, 3, 4, 5, 6, 8, 9, ...};. - Method 2 (Nested): This is clearer. Each inner
{}is a row.int a[3][3] = { {0, 1, 2}, // Row 0 {3, 4, 5}, // Row 1 {6, 7, 8} }; // Row 2
- Method 1 (Flat):
-
Accessing Elements:
- You need two indices:
a[rowIndex][columnIndex]. - Both indices start at 0.
a[0][0]is the top-left element (e.g.,0in the example).a[1][1]is the element in the 2nd row, 2nd column (e.g.,4).a[2][2]is the element in the 3rd row, 3rd column (e.g.,8).
- You need two indices:
-
Using Nested Loops: To access every element in a 2D array, you must use nested loops (a loop inside another loop).
- The outer loop (e.g.,
i) iterates through the rows. - The inner loop (e.g.,
j) iterates through the columns for each row.
- The outer loop (e.g.,
-
Example (Reading from User):
for(int i=0; i<3; i++) { // Outer loop (rows) for(int j=0; j<3; j++) { // Inner loop (columns) cin >> a[i][j]; } } -
Example (Printing):
for(int i=0; i<3; i++) { for(int j=0; j<3; j++) { cout << a[i][j]; } cout << endl; // New line after each row }
محتويات المحاضرة
اختبر فهمك للمحاضرة
تصحيح فوري بالذكاء الاصطناعي