Multidimensional Arrays
Part of the Fundamentals section of Coddy's C journey — lesson 56 of 63.
A multidimensional array is an array of arrays. In C, you can create a 2D array (the most common multidimensional array), essentially a table with rows and columns.
Declare a 2D array:
int matrix[3][4];This creates a 2D array with 3 rows and 4 columns.
You can initialize a 2D array when declaring it:
int matrix[3][4] = {
{1, 2, 3, 4}, // First row
{5, 6, 7, 8}, // Second row
{9, 10, 11, 12} // Third row
};To access elements in a 2D array, use two indices:
int value = matrix[1][2]; // Accesses row 1, column 2 (value will be 7)To modify an element in a 2D array:
matrix[0][3] = 100; // Changes the element at row 0, column 3 to 100You can also use nested loops to access all elements in a 2D array:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n"); // New line after each row
}Challenge
EasyCreate a function called printDiagonal that takes a 2D square array (where the number of rows equals the number of columns) and prints the elements on the main diagonal (from top-left to bottom-right).
The function should:
- Take an integer array and its size as parameters.
- Print each element on the main diagonal (where row index equals column index).
- Separate each element with a space.
For example, given the array:
1 2 3 4 5 6 7 8 9
The function should print: 1 5 9
Cheat sheet
A multidimensional array is an array of arrays. In C, you can create a 2D array with rows and columns.
Declare a 2D array:
int matrix[3][4];Initialize a 2D array when declaring:
int matrix[3][4] = {
{1, 2, 3, 4}, // First row
{5, 6, 7, 8}, // Second row
{9, 10, 11, 12} // Third row
};Access elements using two indices:
int value = matrix[1][2]; // Accesses row 1, column 2 (value will be 7)Modify an element:
matrix[0][3] = 100; // Changes the element at row 0, column 3 to 100Use nested loops to access all elements:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n"); // New line after each row
}Try it yourself
#include <stdio.h>
// Function to print the diagonal elements of a square matrix
void printDiagonal(int matrix[][100], int size) {
// Write your code here
}
int main() {
int size;
scanf("%d", &size);
int matrix[100][100];
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
scanf("%d", &matrix[i][j]);
}
}
printDiagonal(matrix, size);
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge