Access Two-Dimensional Array Elements
In this step, you'll learn how to access individual elements in a two-dimensional array using indexing and nested loops in C.
Let's update our previous file to demonstrate element access.
Add the following code to explore different ways of accessing array elements:
#include <stdio.h>
int main() {
// Create a 3x4 student grades array
int grades[3][4] = {
{85, 92, 78, 90}, // First student's grades
{76, 88, 95, 82}, // Second student's grades
{63, 71, 89, 93} // Third student's grades
};
// Method 1: Direct element access
printf("First student's first grade: %d\n", grades[0][0]);
printf("Second student's third grade: %d\n", grades[1][2]);
// Method 2: Accessing elements using nested loops
printf("\nAll grades using nested loops:\n");
for (int student = 0; student < 3; student++) {
for (int subject = 0; subject < 4; subject++) {
printf("Student %d, Subject %d: %d\n",
student + 1, subject + 1, grades[student][subject]);
}
}
// Method 3: Modifying array elements
grades[2][3] = 95; // Update last grade of third student
printf("\nUpdated third student's last grade: %d\n", grades[2][3]);
return 0;
}
Compile and run the program:
gcc two_dimensional_arrays.c -o two_dimensional_arrays
./two_dimensional_arrays
Example output:
First student's first grade: 85
Second student's third grade: 95
All grades using nested loops:
Student 1, Subject 1: 85
Student 1, Subject 2: 92
Student 1, Subject 3: 78
Student 1, Subject 4: 90
Student 2, Subject 1: 76
Student 2, Subject 2: 88
Student 2, Subject 3: 95
Student 2, Subject 4: 82
Student 3, Subject 1: 63
Student 3, Subject 2: 71
Student 3, Subject 3: 89
Student 3, Subject 4: 95
Updated third student's last grade: 95
Key points about accessing two-dimensional array elements:
- Use two indices:
array[row][column]
- First index represents the row (vertical)
- Second index represents the column (horizontal)
- Indexing starts at 0
- Nested loops are useful for traversing entire arrays
- You can directly read and modify individual elements