Print a 2D Array in C
To print a 2D array in C, we use nested loops where the outer loop iterates over the rows and the inner loop iterates over the columns. Each element is accessed using its row and column index, and printed using printf()
.
Examples of Printing a 2D Array
1. Printing a 2D Integer Array
In this example, we declare a 2D integer array and use nested loops to print its elements in a tabular format.
main.c
</>
Copy
#include <stdio.h>
int main() {
int matrix[2][3] = { {1, 2, 3}, {4, 5, 6} };
// Printing the 2D array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n"); // Move to the next row
}
return 0;
}
Explanation:
- We declare a 2D integer array
matrix
with 2 rows and 3 columns. - We use an outer loop (
i
) to iterate over the rows (0 to 1). - The inner loop (
j
) iterates over the columns (0 to 2). - Inside the inner loop,
printf()
prints each element of the array. - After each row,
printf("\n")
ensures a new line for proper formatting.
Output:
1 2 3
4 5 6
2. Printing a 2D Character Array
In this example, we declare a 2D character array (a list of words) and print it row by row.
main.c
</>
Copy
#include <stdio.h>
int main() {
char words[3][10] = { "Hello", "World", "C" };
// Printing the 2D character array
for (int i = 0; i < 3; i++) {
printf("%s\n", words[i]);
}
return 0;
}
Explanation:
- We declare a 2D character array
words
with 3 rows, each capable of holding a word of up to 9 characters plus the null terminator. - The outer loop (
i
) iterates over the rows (0 to 2). - We use
printf("%s\n", words[i])
to print each word on a new line.
Output:
Hello
World
C
3. Printing a 3×3 Matrix with Row and Column Index
In this example, we print a 3×3 integer matrix with row and column indices to show element positions.
main.c
</>
Copy
#include <stdio.h>
int main() {
int matrix[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
// Printing the matrix with row and column indices
printf("Matrix with indices:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("(%d,%d):%d ", i, j, matrix[i][j]);
}
printf("\n");
}
return 0;
}
Explanation:
- We declare a 3×3 integer array
matrix
. - The outer loop (
i
) iterates over the rows (0 to 2). - The inner loop (
j
) iterates over the columns (0 to 2). - We use
printf("(%d,%d):%d ", i, j, matrix[i][j])
to print each element along with its row and column index. printf("\n")
is used after each row to format the output properly.
Output:
Matrix with indices:
(0,0):1 (0,1):2 (0,2):3
(1,0):4 (1,1):5 (1,2):6
(2,0):7 (2,1):8 (2,2):9
Conclusion
In this tutorial, we explored different ways to print a 2D array in C:
- Printing an Integer 2D Array: Using nested loops to print elements row by row.
- Printing a Character 2D Array: Using
printf("%s")
to print strings stored in a 2D array. - Printing with Row and Column Indices: Displaying indices along with values.