Deck of cards structure C programming. I\'m really struggling trying to write th
ID: 3846828 • Letter: D
Question
Deck of cards structure C programming. I'm really struggling trying to write the program for this assignment, can anyone help?
Write a structure (struct card) that will represent a card in a standard deck of playing cards. You will need to represent both the suit (clubs, diamonds, hearts or spades) as well as the rank ( A, K, Q, J, 10, 9, 8, 7, 6, 5, 6, 7, 2) of each card. Note that a deck of playing cards can be represented as an array declared as
struct card deck[52];
Write a function that will perform a perfect shuffle on a deck of cards represented using the data structures from part a. In a perfect shuffle, the deck is broken exactly in half and rearranged so that the first card is followed by the 27th card, followed by the second card, followed by the 28th card, and so on.
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
struct card{
int suit; // 0 for clubs,1 for diamonds,2 for hearts and 3 for spades
int rank; // 13 for A, 12 for K,11 for Q,10 for J
};
//Perfect shuffle deck function
void perfect_shuffle(struct card deck[])
{
int i,j;
struct card temp[52];
for(i=0,j=0;i<26;i+=1,j+=2)
{
temp[j].suit = deck[i].suit;
temp[j].rank = deck[i].rank;
temp[j+1].suit = deck[i+26].suit;
temp[j+1].rank = deck[i+26].rank;
}
for(i=0;i<52;i+=1)
{
deck[i].suit = temp[i].suit;
deck[i].rank = temp[i].rank;
}
}
//Function to print the deck
void print_deck(struct card deck[]) {
int i=0;
for(i=0;i<52;i+=1) {
if(i==0) printf("Cards in deck are: ");
printf("Rank: %d , Suit: %d ", deck[i].rank,deck[i].suit);
if(i==51) printf(" ");
}
}
int main()
{
int i=0;
struct card deck[52];
for(i=0;i<52;i+=1)
{
if(i<13) {
deck[i].suit = 0;
deck[i].rank = i+1;
} else if (i<26) {
deck[i].suit = 1;
deck[i].rank = i-13+1;
} else if (i<39) {
deck[i].suit = 2;
deck[i].rank = i-26+1;
} else {
deck[i].suit = 3;
deck[i].rank = i-39+1;
}
}
printf("==================Orginial Deck:============================== ");
print_deck(deck);
perfect_shuffle(deck);
printf("==================Shuffled deck:============================= ");
print_deck(deck);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.