![]() |
VOOZH | about |
A deck of cards is a collection of 52 playing cards in which each card is uniquely identified by its suit and rank, there are four suits: heart, diamond, club and spade each having 13 ranks: Ace, 2 to 10, jack, queen, and king. In this article, we will learn how to represent a deck of cards using a C++ array.
In C++, we can make the use of classes to represent a deck of cards as it provides a structured and efficient way to represent a deck of cards. This arrangement allows for easy access, manipulation, shuffling, and allotment of cards to players, as the deck internally uses array the user defined data type card.
- Define a Card class with suit and rank as members.
- Create a Deck class to manage the deck of cards. Inside it, we create an array of cards to store the deck of card.
- Create and Initialize the suits and ranks arrays with the names of the suits and ranks.
- Initialize the deck of cards in a nested loop.
- For each combination of suit and rank, create a card and add it to the deck.
- Finally, using a loop, print each card in the deck.
Below is the C++ program that represents a deck of cards using an array
Output
hearts Ace | hearts 2 | hearts 3 | hearts 4 | hearts 5 | hearts 6 | hearts 7 | hearts 8 | hearts 9 | hearts 10 | hearts Jack | hearts Queen | hearts King
diamonds Ace | diamonds 2 | diamonds 3 | diamonds 4 | diamonds 5 | diamonds 6 | diamonds 7 | diamonds 8 | diamonds 9 | diamonds 10 | diamonds Jack | diamonds Queen | diamonds King
clubs Ace | clubs 2 | clubs 3 | clubs 4 | clubs 5 | clubs 6 | clubs 7 | clubs 8 | clubs 9 | clubs 10 | clubs Jack | clubs Queen | clubs King
spades Ace | spades 2 | spades 3 | spades 4 | spades 5 | spades 6 | spades 7 | spades 8 | spades 9 | spades 10 | spades Jack | spades Queen | spades KingTime Complexity: O(1), It is constant because the deck size is fixed (52).
Auxiliary Space: O(1)