How to print 2D Arrays in C++?

You are printing std::endl after each number. If you want to have 1 row per line, then you should print std::endl after each row. Example:

#include <iostream>

int main(void)
{
    int myArray[][4] = { {1,2,3,4}, {5,6,7,8} };
    int width = 4, height = 2;

    for (int i = 0; i < height; ++i)
    {
        for (int j = 0; j < width; ++j)
        {
            std::cout << myArray[i][j] << ' ';
        }
        std::cout << std::endl;
    }
}

Also note that writing using namespace std; at the beginning of your files is considered bad practice since it causes some of user-defined names (of types, functions, etc.) to become ambiguous. If you want to avoid exhausting prefixing with std::, use using namespace std; within small scopes so that other functions and other files are not affected.

Leave a Comment