unexpectedprogramming
unexpectedprogramming

Reputation: 49

printing 2d arrays in c++

i am trying to make a mach chess board using 2D arrays to draw it this is what i have so far

 #include <iostream>

using namespace std;

    int main()
    {

        char table[8][9]={"RkBKQBkR", "pppppppp", "        ", "        ", "         ", "        ", "pppppppp", "RkBKQBkR" } ;

        for (int rows=0; rows<8; rows++)
        {
            for (int col=0; col<8; col++)
            {
                  cout << table[rows][col] ;
            }
        }


        return 0;
}

how would i add lines (|) and (-) between the objects of the array ? the output is RkBKQBkRpppppppp ppppppppRkBKQBkR

Upvotes: 0

Views: 87

Answers (3)

Huy
Huy

Reputation: 3363

You should use 2 for-loops (outer & inner) statement with if-else condition to decide to print or not.

Find "|" & "-" character in ASCII table to have the nice chess board.

Hope this help!

Upvotes: 0

CJCombrink
CJCombrink

Reputation: 3950

Suggestion: Since it is C++, start by looking at the STL containers, vectors etc since the way you define the array is more the C way.

That aside, to add the aditional text:

std::vector<std::string> table ={"RkBKQBkR", "pppppppp", "        ", "        ", "         ", "        ", "pppppppp", "RkBKQBkR" };
for (int rows=0; rows<8; rows++)
{
    cout << "|";
    for (int col=0; col<8; col++)
    {
        cout << table[rows][col] << "|";
    }
    cout << endl;
    for(int i = 0; i < 8; ++i) { cout << "--"; }
    cout << "-" << endl;
}

My code uses vector of strings since your code with the char[][] did not compile on my computer.

Upvotes: 1

Khaja Sharfuddin
Khaja Sharfuddin

Reputation: 1

Print | this in the outer for-loop and - this in the inner for-loop

Upvotes: 0

Related Questions