In: Computer Science
#include <stdio.h>
const int DECK_SIZE = 52;
int deck[DECK_SIZE];
int main(void) {
/* Populate the deck */
for(int i = 0; i < DECK_SIZE; i++) {
deck[i] = i + 1;
}
/* Get the cut position as an integer input */
/* Verify that the input is valid */
/* Cut the deck */
/* Print the resulting deck with one element on each line */
return 0;
}
Write a program that "cuts" a deck of 52 playing cards. Given a cut position, the process of cutting the deck refers to taking all cards before the cut position and moving them to the end of the deck. The order of the cards is maintained. For example, if the deck is cut at position 25, the first 25 cards of the deck are moved to become the last 25 cards of the deck. The new first card in the deck is card 26, and the new last card of the deck is card 25.
The deck of cards is represented as a 52-element integer array, with values 1 through 52 representing the different cards. The initial population of the deck is done for you.
Your program should accept a single integer input, which is the cut position. If the input is less than 1 or greater than 52, your program should print "ERROR" and exit. Otherwise, after performing the cut, your program should print out the new deck, with one card value on each line.
Please use C language only. Please make it simple as this is an introductory C programming course
Dear student, according to the question, the solution is as follows:
As you said, it is an introductory C programming course, I have used extra temporary array to implement this. In general, without using extra array also, we can do this problem.
Program:
#include <stdio.h>
#include <stdlib.h> // for the exit(0) function
const int DECK_SIZE = 52;
int deck[DECK_SIZE];
int main()
{
int cut,i;
/* Populate the deck */
for(int i = 0; i < DECK_SIZE; i++)
{
deck[i] = i + 1;
}
/* Get the cut position as an integer input */
printf("Enter the cut position : ");
scanf("%d",&cut);
/* Verify that the input is valid */
if(cut <= 1 || cut >= DECK_SIZE)
{
printf("ERROR : Invalid Card");
exit(0);
}
/* if valid card, proceed with the cut process */
else
{
/* take temporary array to store the deck values up to cut */
int temp[cut];
for(i = 0;i<cut;i++)
temp[i] = deck[i];
for ( i = 0; i < DECK_SIZE; i++)
{
deck[i] = deck[cut + i];
}
/* load the temp array values to the deck array */
int r = DECK_SIZE - cut;
for(int i = 0;i<cut;i++)
{
deck[r++] = temp[i];
}
}
/* Print the resulting deck with one element on each line */
for(int i =0; i<52;i++)
{
printf("%d ",deck[i]);
}
return 0;
}
Output:
Thank you, if at all any doubts, feel free to contact through the comment section.