[Solved] How to define a multidimensional array in C++ with ‘n’ rows and ‘m’ columns and iterate values using For Loop?


You can’t declare the array unknown size. You must do it dynamically.

#include <iostream>
using namespace std;

int main()
{
    int n = 0, m = 0;

    //. Get the matrix's size
    while (true)
    {
        cout << "Input the row count: "; cin >> n;
        cout << "Input the column count: "; cin >> m;

        if (n < 1 || m < 1)
        {
            cout << "Invalid values. Please retry." << endl;
            continue;
        }

        break;
    }

    //. Allocate multi-dimensional array dynamically.
    int ** mat = new int *[n];
    for (int i = 0; i < n; i++)
    {
        mat[i] = new int[m];
    }

    //. Receive the elements.
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cout << "Input the element of (" << i + 1 << "," << j + 1 << "): ";
            cin >> mat[i][j];
        }
    }

    //. Print matrix.
    cout << endl << "Your matrix:" << endl;
    for (int i = 0; i < n; i++)
    {       
        for (int j = 0; j < m; j++)
        {
            cout << mat[i][j] << "\t";
        }
        cout << std::endl;
    }

    //. Free memories.
    for (int i = 0; i < n; i++)
    {
        delete[] mat[i];
    }
    delete[] mat;

    return 0;
}

If you like to use stl, it can be simple.

#include <iostream>
#include <vector>
using namespace std;

using ROW = vector<int>;
using MATRIX = vector<ROW>;

int main()
{
    int n = 0, m = 0;
    MATRIX mat;

    cin >> n >> m;

    for (int i = 0; i < n; i++)
    {
        ROW row;
        row.resize(m);

        for (int j = 0; j < m; j++)
        {
            cin >> row[j];
        }
        mat.push_back(row);
    }

    for (auto & row : mat)
    {
        for (auto & iter : row)
        {
            cout << iter << "\t";
        }
        cout << endl;
    }

    return 0;
}

0

solved How to define a multidimensional array in C++ with ‘n’ rows and ‘m’ columns and iterate values using For Loop?