CFORBEGINNERS.COM


Card Game in C

Here is a simple card game that simulates a random deck of cards. The program simulates drawing however many cards you choose and prints what cards you drew, jack of hearts, queen of diamonds, etc. This card game has much room for improvement, this is a good starting point, if anyone would like to modify this program feel free.

#include <stdio.h>
#include <stdlib.h>
#include <time.h> /*This is the time header file, you must include this when you are using random numbers*/



int rand_int(int n);
void draw_a_card();

/*Notice how char *suits and char *ranks are global variables*/
char *suits[4]={"spades","clubs","diamonds","hearts"};

char *ranks[13]={"ace","two","three","four","five","six","seven","eight","nine","ten","jack",
"queen","king"};



int main()
{

    int x,y;
    srand(time(NULL)); /*This is to set the seed for random numbers*/
    do{
    printf("\nEnter a number of cards to draw (Press 0 to exit)\n");
    scanf("%i",&y);
     if(y==0)
        break;

    for(x=1; x<=y; x++)
       {
           draw_a_card(); /*If you wanted to draw five cards this function would be called five individual times*/
} }while(1); return 0; } void draw_a_card() /*void because we aren't returning a value*/ { int r,s; r=rand_int(13); /*Receives a number back from 0 to 12*/ s=rand_int(4); /*Receives a number back from 0 to 3*/ printf("\n%s of %s\n",ranks[r],suits[s]); } int rand_int(int n) { return rand()%n; /*Returns a number from 0 to N-1*/ }