convert 2d array to 1d c++

To convert a 2D array to a 1D array in C++, you can follow these steps:

  1. Declare and initialize the 2D array: Start by declaring and initializing the 2D array with the desired values. For example, let's consider a 2D array of size 3x3:
int arr2D[3][3] = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};
  1. Calculate the total number of elements: Determine the total number of elements in the 2D array by multiplying the number of rows with the number of columns. In this case, there are 3 rows and 3 columns, so the total number of elements is 3 * 3 = 9.
int rows = 3;
int columns = 3;
int totalElements = rows * columns;
  1. Declare and initialize the 1D array: Declare a 1D array with a size equal to the total number of elements in the 2D array. In this case, the 1D array size will be 9.
int arr1D[9];
  1. Convert the 2D array to a 1D array: Iterate over each element of the 2D array and copy it to the corresponding index in the 1D array. You can use nested loops to iterate over the rows and columns of the 2D array.
int index = 0;
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < columns; j++) {
        arr1D[index] = arr2D[i][j];
        index++;
    }
}

After these steps, the 2D array will be successfully converted to a 1D array. The elements in the 1D array will be in the same order as if you had traversed the 2D array row by row.

Here's the complete code:

#include <iostream>

int main() {
    int arr2D[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    int rows = 3;
    int columns = 3;
    int totalElements = rows * columns;

    int arr1D[9];

    int index = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            arr1D[index] = arr2D[i][j];
            index++;
        }
    }

    // Printing the 1D array
    for (int i = 0; i < totalElements; i++) {
        std::cout << arr1D[i] << " ";
    }

    return 0;
}

This code will output: 1 2 3 4 5 6 7 8 9