Hi all,
My teacher used the following example to teach us about multiple-dimension arrays:
Code:
/* Deals a random hand of cards */
#include <stdbool.h> /* C99 only */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_SUITS 4
#define NUM_RANKS 13
int main(void)
{
bool in_hand[NUM_SUITS][NUM_RANKS] = {false};
int num_cards, rank, suit;
const char rank_code[] = {'2','3','4','5','6','7','8',
'9','t','j','q','k','a'};
const char suit_code[] = {'c','d','h','s'};
srand((unsigned) time(NULL));
printf("Enter number of cards in hand: ");
scanf("%d", &num_cards);
printf("Your hand:");
while (num_cards > 0) {
suit = rand() % NUM_SUITS; /* picks a random suit */
rank = rand() % NUM_RANKS; /* picks a random rank */
if (!in_hand[suit][rank]) {
in_hand[suit][rank] = true;
num_cards--;
printf(" %c%c", rank_code[rank], suit_code[suit]);
}
}
printf("\n");
return 0;
}
The part that I don't understand is this:
Code:
suit = rand() % NUM_SUITS;
rank = rand() % NUM_RANKS;
There are 4 suits, ranging from 0 to 3, and 13 ranks, ranging from 0 to 12. The value returned by the statements above can only return 0 to 9; doesn't that mean it's going to leave out some ranks, and possibility going out of bound for suits?
Obviously I'm new to C (and programming in general), and I've only gotten to arrays, so please take that into consideration when you explain things.
Much thanks!