# Draw Five Cards (Poker I)

To code a card game, you must start with the deck: 52 cards divided into 4 suits each consisting of 10 number cards and three face cards. Seems easy.

I’ve written before about simulating a deck of cards, but not really using them to play a game. Further, the deck must be randomized so you can’t draw the same card twice. These steps come first.

The following code creates an array `cards[]` consisting of 52 int values. It’s initialized to all zeros, where zero indicates a card hasn’t been drawn. When a card is drawn, the corresponding array element is set to 1.

```#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define CARDS 52

int main()
{
int deck[CARDS];
int x;

/* seed the randomizer */
srand((unsigned)time(NULL));

/* initialize the deck */
/* 0 = card not drawn
1 = card drawn */
for( x=0; x<CARDS; x++)
deck[x] = 0;

return(0);
}```

The code seeds the randomizer at Line 13, which is used later. The for loop at Line 18 initializes array `deck[]` to all zeros. This code has no output.

In the next modification, I add the draw() function. This function looks for elements in array `deck[]` that haven’t been drawn. Once found, it sets that element to 1 (meaning the card has been drawn) and returns the card’s element value.

```#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define CARDS 52

int draw(int d[]);

int main()
{
int deck[CARDS];
int x,c;

/* seed the randomizer */
srand((unsigned)time(NULL));

/* initialize the deck */
/* 0 = card not drawn
1 = card drawn */
for( x=0; x<CARDS; x++)
deck[x] = 0;

c = draw(deck);
printf("You drew the %d\n",c);

return(0);
}

int draw(int d[])
{
int r;
/* search for an available card */
while(1)
{
r = rand() % CARDS;
if( d[r] == 0 )
break;
}

d[r] = 1;

return(r);
}```

The while loop in the draw() function endlessly spins, looking for an element in array `d[]` (the passed deck of cards) that hasn’t yet been drawn. When one is found, the loop breaks. The given element is set to 1, then the element value is returned.

Here’s a sample run:

`You drew the 16`

Drawing “the 16” doesn’t many anything to someone familiar with the standard deck of playing cards. The draw() function works, but it needs more heft if the value returned is to be meaningful to a player as well as to the rest of the code when a card game is implemented.

In next week’s Lesson, I upgrade the draw() function to report a card’s face value and suit.