C/C++ How to Convert 2D Array to 1D Array?

In this post, we will discuss how to convert a 2D array to a 1D array in C/C++.

Row-Major Order

Row-Major order means we insert elements of the 2D array to 1D array row-wise. First, we insert elements of the 1st row of the 2D array to the 1D array, then elements of 2nd row and so on.

For example,

Input
{
     { 1,1,1 },
     { 2,2,2 },
     { 3,3,3 }
}

Output
{ 1, 1, 1, 2, 2, 2, 3, 3, 3 }

Program

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
	int arr2D[10][10], * arr1D;
	int n, m, i, j;

	// Enter Matrix A
	printf("Enter Number of Rows: ");
	scanf("%d", &n);
	printf("Enter Number of columns: ");
	scanf("%d", &m);

	printf("Enter 2D Array: \n");
	for (i = 0; i < n; ++i) {
		for (j = 0; j < m; ++j) {
			scanf("%d", &arr2D[i][j]);
		}
	}

	// allocating memeory to 1D dynamically
	// size of 1D array will be n*m
	arr1D = (int*)malloc(n * m * sizeof(int));

	for (i = 0; i < n; ++i) {
		for (j = 0; j < m; ++j) {
			// mapping 1D array to 2D array
			arr1D[i * m + j] = arr2D[i][j];
		}
	}

	printf("1D Array: ");

	for (i = 0; i < n * m; ++i) {
		printf("%d ", arr1D[i]);
	}

}

Output

Enter Number of Rows: 3
Enter Number of columns: 3
Enter 2D Array:
1 1 1
2 2 2
3 3 3
1D Array: 1 1 1 2 2 2 3 3 3

Column-Major Order

In column-major order, we first insert the elements of the 1st column of the 2D array to the 1D array, then the elements of the 2nd column and so on.

For example,

Input
{
    { 1,2,5 },
    { 1,3,6 },
    { 1,4,7 }
}

Output
{ 1, 1, 1, 2, 3, 4, 5, 6, 7 }

Program

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int main()
{
	int arr2D[10][10], * arr1D;
	int n, m, i, j;

	// Enter Matrix A
	printf("Enter Number of Rows: ");
	scanf("%d", &n);
	printf("Enter Number of columns: ");
	scanf("%d", &m);

	printf("Enter 2D Array: \n");
	for (i = 0; i < n; ++i) {
		for (j = 0; j < m; ++j) {
			scanf("%d", &arr2D[i][j]);
		}
	}

	// allocating memeory to 1D dynamically
	// size of 1D array will be n*m
	arr1D = (int*)malloc(n * m * sizeof(int));

	for (j = 0; j < m; ++j) {
		for (i = 0; i < n; ++i) {
			// mapping 1D array to 2D array
			arr1D[j * n + i] = arr2D[i][j];
		}
	}

	printf("1D Array: ");

	for (i = 0; i < n * m; ++i) {
		printf("%d ", arr1D[i]);
	}

}

Output

Enter Number of Rows: 3
Enter Number of columns: 3
Enter 2D Array:
1 2 5
1 3 6
1 4 7
1D Array: 1 1 1 2 3 4 5 6 7

Read
Program to remove alternate digits of an integer
C Program to transpose matrix in-place (without extra space)
Program of Matrix Addition (Recursion)
Program to reverse stack using queue
C Program to Find hypotenuse of a triangle without using math.h library

Leave a Comment

Your email address will not be published. Required fields are marked *