Flatten a 2D Array into a 1D Array in C
To flatten a 2D array into a 1D array in C, we need to traverse the 2D array row-wise or column-wise and store its elements in a 1D array. This process converts a matrix-like structure into a linear sequence of values. We achieve this using nested loops that iterate over rows and columns while maintaining an index for the 1D array.
Examples to Flatten a 2D Array
1. Flattening a 2D Array Row-wise
In this example, we will take a 2D array and flatten it row-wise into a 1D array. The nested loop will iterate over rows first, then columns, copying elements sequentially into the 1D array.
main.c
#include <stdio.h>
#define ROWS 2
#define COLS 3
int main() {
int matrix[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}};
int flatArray[ROWS * COLS];
int index = 0;
// Flattening the 2D array row-wise
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
flatArray[index++] = matrix[i][j];
}
}
// Printing the flattened 1D array
for (int i = 0; i < ROWS * COLS; i++) {
printf("%d ", flatArray[i]);
}
return 0;
}
Explanation:
- We define a 2D array
matrix
of size2x3
with values{{1, 2, 3}, {4, 5, 6}}
. - We declare a 1D array
flatArray
of sizeROWS * COLS
to store the flattened values. - We use a nested loop to iterate over rows and columns of the 2D array.
- Inside the inner loop, we copy elements from
matrix[i][j]
toflatArray[index]
, incrementingindex
each time. - Finally, we print the contents of the 1D array.
Output:
1 2 3 4 5 6
2. Flattening a 2D Array Column-wise
In this example, we will flatten a 2D array column-wise instead of row-wise. This means we traverse elements column by column instead of row by row.
main.c
#include <stdio.h>
#define ROWS 2
#define COLS 3
int main() {
int matrix[ROWS][COLS] = {{1, 2, 3}, {4, 5, 6}};
int flatArray[ROWS * COLS];
int index = 0;
// Flattening the 2D array column-wise
for (int j = 0; j < COLS; j++) {
for (int i = 0; i < ROWS; i++) {
flatArray[index++] = matrix[i][j];
}
}
// Printing the flattened 1D array
for (int i = 0; i < ROWS * COLS; i++) {
printf("%d ", flatArray[i]);
}
return 0;
}
Explanation:
- We define the 2D array
matrix
of size2x3
with the same values. - We declare a 1D array
flatArray
of sizeROWS * COLS
. - Instead of iterating row-wise, we swap the loop order and iterate column-wise first.
- We copy elements from
matrix[i][j]
intoflatArray[index]
in column-major order. - Finally, we print the 1D array.
Output:
1 4 2 5 3 6
Conclusion
In this tutorial, we learned how to flatten a 2D array into a 1D array using two different approaches:
- Row-wise Flattening: Extracts elements from left to right, top to bottom.
- Column-wise Flattening: Extracts elements from top to bottom, left to right.
Both approaches use nested loops to iterate through the 2D array and store values in a 1D array sequentially.