what i did before writing the following function is that i alloted numbers 1 to 52 to a deck of 52 cards(in a 2d array with four rows and 13 columns).now i want to print the cards holding numbers (in ascending order) in a way that there are 2 displays in a line...
void DeckOfCards::deal()
{
// initialize suit array
static const char *suit[ 4 ] =
{ "Hearts", "Diamonds", "Clubs", "Spades" };
// initialize face array
开发者_运维百科static const char *face[ 13 ] =
{ "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven",
"Eight", "Nine", "Ten", "Jack", "Queen", "King" };
// for each of the 52 cards
for ( int card = 1; card <= 52; card++ )
{
// loop through rows of deck
for ( int row = 0; row <= 3; row++ )
{
// loop through columns of deck for current row
for ( int column = 0; column <= 12; column++ )
{
// if slot contains current card, display card
if ( deck[ row ][ column ] == card )
{
cout << setw( 5 ) << right << face[ column ]
<< " of " << setw( 8 ) << left << suit[ row ]
<< ( card % 2 == 0 ? '\n' : '\t' );
} // end if
} // end innermost for
} // end inner for
} // end outer for
} // end function deal
but if i change the order of for statemants such that row comes first then column and then card...what i get is a completely different layout of the output....i.e. no two outputs in a single line....it is something completely disordered...why plz tell me?
The card loop is probably not necessary. Instead, inside the inner loop, calculate card from row and column.
Switching the order of row and column loops is expected to change the output (row major or column major)
If you do row first then column then card, you will get all the hearts first, then all the diamonds, clubs and spades, and in order Ace, Deuce, Three .. King
Whether or not it puts in an extra column depends on "card" which is where it is randomly in the pack, so it is almost like tossing a coin whether it will give you a newline or not, except that you are guaranteed it will do so exactly 26 times.
精彩评论