21
Week 14 2007/May/28 C: How to Program C: How to Program

C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

  • Upload
    tranthu

  • View
    222

  • Download
    0

Embed Size (px)

Citation preview

Page 1: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

1

Week 142007/May/28

C: How to ProgramC: How to Program

Page 2: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

2

7.9 Arrays of Pointers• Arrays can contain pointers• For example: an array of strings

char *suit[ 4 ] = { "Hearts", "Diamonds","Clubs", "Spades" };

– Strings are pointers to the first character– char * – each element of suit is a pointer to a char– The strings are not actually stored in the array suit, only pointers

to the strings are stored

– suit array has a fixed size, but strings can be of any size

suit[3]

suit[2]

suit[1]

suit[0] ’H’ ’e’ ’a’ ’r’ ’t’ ’s’ ’\0’

’D’ ’i’ ’a’ ’m’ ’o’ ’n’ ’d’ ’s’ ’\0’

’C’ ’l’ ’u’ ’b’ ’s’ ’\0’

’S’ ’p’ ’a’ ’d’ ’e’ ’s’ ’\0’

Page 3: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

3

7.10 Case Study: A Card Shuffling and Dealing Simulation

• Card shuffling program– Use array of pointers to strings– Use double scripted array (suit, face)

– The numbers 1-52 go into the array• Representing the order in which the cards are dealt

deck[ 2 ][ 12 ] represents the King of Clubs

HeartsDiamonds

ClubsSpades

0123

Ace

Two

Three

Four

Five

Six

Seven

Eight

Nine

Ten

Jack

Queen

King

0 1 2 3 4 5 6 7 8 9 10 11 12

Clubs King

Page 4: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

4

7.10 Case Study: A Card Shuffling and Dealing Simulation

• Pseudocode– Top level:

Shuffle and deal 52 cards– First refinement:

Initialize the suit arrayInitialize the face arrayInitialize the deck arrayShuffle the deckDeal 52 cards

Page 5: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

5

7.10 Case Study: A Card Shuffling and Dealing Simulation

– Second refinement• Convert shuffle the deck to

For each of the 52 cardsPlace card number in randomly selected unoccupied slot of deck

• Convert deal 52 cards toFor each of the 52 cards

Find card number in deck array and print face and suit of card

Page 6: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

6

7.10 Case Study: A Card Shuffling and Dealing Simulation

– Third refinement• Convert shuffle the deck to

Choose slot of deck randomlyWhile chosen slot of deck has been previously chosen

Choose slot of deck randomlyPlace card number in chosen slot of deck

• Convert deal 52 cards toFor each slot of the deck array

If slot contains card numberPrint the face and suit of the card

Page 7: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

7

/* Fig. 7.24: fig07_24.cCard shuffling dealing program */

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

/* prototype */void shuffle( int wDeck[ ][ 13 ] );void deal( const int wDeck[ ][ 13 ], const char *wFace[ ],

const char *wSuit[ ] );

int main(){

/* initialize suit array */const char *suit[ 4 ] = { "Hearts", "Diamonds", "Clubs", "Spades" };

/* initialize face array */const char *face[ 13 ] =

{ "Ace", "Deuce", "Three", "Four", "Five", "Six", "Seven", "Eight","Nine", "Ten", "Jack", "Queen", "King" };

/* initialize deck array */int deck[ 4 ][ 13 ] = { 0 };

Page 8: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

8

srand( time( 0 ) ); /* seed random-number generator */

shuffle( deck );deal( deck, face, suit );

return 0; /* indicates successful termination */

} /* end main */

/* shuffle cards in deck */void shuffle( int wDeck[ ][ 13 ] ){

int row; /* row number */int column; /* column number */int card; /* counter */

/* for each of the 52 cards, choose slot of deck randomly */for ( card = 1; card <= 52; card++ ) {

/* choose new random location until unoccupied slot found */do {

row = rand() % 4;column = rand() % 13;

} while( wDeck[ row ][ column ] != 0 ); /* end do...while */

Page 9: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

9

/* place card number in chosen slot of deck */wDeck[ row ][ column ] = card;

} /* end for */

} /* end function shuffle */

/* deal cards in deck */void deal( const int wDeck[ ][ 13 ], const char *wFace[ ],

const char *wSuit[ ] ){

int row; /* row number */int column; /* column number */int card; /* card counter */

/* deal each of the 52 cards */for ( card = 1; card <= 52; card++ ) {

/* loop through rows of wDeck */for ( row = 0; row <= 3; row++ ) {

/* loop through columns of wDeck for current row */for ( column = 0; column <= 12; column++ ) {

/* if slot contains current card, display card */if ( wDeck[ row ][ column ] == card ) {

Page 10: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

10

printf( "%5s of %-8s%c", wFace[ column ], wSuit[ row ],card % 2 == 0 ? '\n' : '\t' );

} /* end if */

} /* end for */

} /* end for */

} /* end for */

} /* end function deal */Nine of Hearts Five of ClubsQueen of Spades Three of SpadesQueen of Hearts Ace of ClubsKing of Hearts Six of SpadesJack of Diamonds Five of SpadesSeven of Hearts King of ClubsThree of Clubs Eight of HeartsThree of Diamonds Four of DiamondsQueen of Diamonds Five of DiamondsSix of Diamonds Five of HeartsAce of Spades Six of HeartsNine of Diamonds Queen of Clubs

Page 11: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

11

Eight of Spades Nine of ClubsDeuce of Clubs Six of ClubsDeuce of Spades Jack of ClubsFour of Clubs Eight of ClubsFour of Spades Seven of SpadesSeven of Diamonds Seven of ClubsKing of Spades Ten of DiamondsJack of Hearts Ace of HeartsJack of Spades Ten of ClubsEight of Diamonds Deuce of DiamondsAce of Diamonds Nine of SpadesFour of Hearts Deuce of HeartsKing of Diamonds Ten of SpadesThree of Hearts Ten of Hearts

Page 12: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

12

7.11 Pointers to Functions

• Pointer to function– Contains address of function– Similar to how array name is address of first element– Function name is starting address of code that defines

function

• Function pointers can be – Passed to functions– Stored in arrays– Assigned to other function pointers

Page 13: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

13

7.11 Pointers to Functions

• Example: bubblesort– Function bubble takes a function pointer

• bubble calls this helper function• this determines ascending or descending sorting

– The argument in bubblesort for the function pointer:int ( *compare )( int a, int b )

tells bubblesort to expect a pointer to a function that takes two ints and returns an int

– If the parentheses were left out:int *compare( int a, int b )

• Defines a function that receives two integers and returns a pointer to a int

Page 14: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

14

/* Fig. 7.26: fig07_26.cMultipurpose sorting program using function pointers */

#include <stdio.h>#define SIZE 10

/* prototype */void bubble( int work[ ], const int size,

int (*compare)( int a, int b ) );int ascending( int a, int b );int descending( int a, int b );

int main(){

int order; /* 1 for ascending order or 2 for descending order */int counter; /* counter */

/* initialize array a */int a[ SIZE ] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };

printf( "Enter 1 to sort in ascending order,\n" "Enter 2 to sort in descending order: " );

scanf( "%d", &order );

printf( "\nData items in original order\n" );

Page 15: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

15

/* output original array */for ( counter = 0; counter < SIZE; counter++ ) {

printf( "%5d", a[ counter ] );} /* end for */

/* sort array in ascending order; pass function ascending as anargument to specify ascending sorting order */

if ( order == 1 ) {bubble( a, SIZE, ascending );printf( "\nData items in ascending order\n" );

} /* end if */ else { /* pass function descending */

bubble( a, SIZE, descending );printf( "\nData items in descending order\n" );

} /* end else */

/* output sorted array */for ( counter = 0; counter < SIZE; counter++ ) {

printf( "%5d", a[ counter ] ); } /* end for */

printf( "\n" );return 0; /* indicates successful termination */

} /* end main */

Page 16: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

16

/* multipurpose bubble sort; parameter compare is a pointer tothe comparison function that determines sorting order */

void bubble( int work[ ], const int size,int (*compare)( int a, int b ) )

{int pass; /* pass counter */int count; /* comparison counter */

void swap( int *element1Ptr, int *element2ptr ); /* prototype */

/* loop to control passes */for ( pass = 1; pass < size; pass++ ) {

/* loop to control number of comparisons per pass */for ( count = 0; count < size - 1; count++ ) {

/* if adjacent elements are out of order, swap them */if ( (*compare)( work[ count ], work[ count + 1 ] ) ) {

swap( &work[ count ], &work[ count + 1 ] );} /* end if */

} /* end for */} /* end for */

} /* end function bubble */

Page 17: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

17

/* swap values at memory locations to which element1Ptr and element2Ptr point */

void swap( int *element1Ptr, int *element2Ptr ){

int hold; /* temporary holding variable */

hold = *element1Ptr;*element1Ptr = *element2Ptr;*element2Ptr = hold;

} /* end function swap */

/* determine whether elements are out of order for an ascendingorder sort */

int ascending( int a, int b ){

return b < a; /* swap if b is less than a */

} /* end function ascending */

/* determine whether elements are out of order for a descendingorder sort */

int descending( int a, int b ){

return b > a; /* swap if b is greater than a */} /* end function descending */

Page 18: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

18

Enter 1 to sort in ascending order,Enter 2 to sort in descending order: 1

Data items in original order2 6 4 8 10 12 89 68 45 37

Data items in ascending order2 4 6 8 10 12 37 45 68 89

Enter 1 to sort in ascending order,Enter 2 to sort in descending order: 2

Data items in original order2 6 4 8 10 12 89 68 45 37

Data items in descending order89 68 45 37 12 10 8 6 4 2

Page 19: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

19

/* Fig. 7.28: fig07_28.cDemonstrating an array of pointers to functions */

#include <stdio.h>

/* prototype */void function1( int a );void function2( int b );void function3( int c );

int main(){

/* initialize array of 3 pointer to functions that each take anint argument and return void */

void (*f[ 3 ])( int ) = { function1, function2, function3 };

int choice; /* variable to hold user's choice */

printf( "Enter a number between 0 and 2, 3 to end: " );scanf( "%d", &choice );

/* process user's choice */while ( choice >= 0 && choice < 3 ) {

Page 20: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

20

/* invoke function at location choice in array f and passchoice as an argument */

(*f[ choice ])( choice );

printf( "Enter a number between 0 and 2, 3 to end: " );scanf( "%d", &choice );

} /* end while */

printf( "Program execution completed.\n" );

return 0; /* indicates successful termination */

} /* end main */

void function1( int a ){

printf( "You entered %d so function1 was called\n\n", a );} /* end function1 */

void function2( int b ){

printf( "You entered %d so function2 was called\n\n", b );} /* end function2 */

Page 21: C: How to Program - 國立中興大學web.nchu.edu.tw/~ycchiang/C_program/C_program_W14a.pdf · 3 7.10 Case Study: A Card Shuffling and Dealing Simulation • Card shuffling program

21

void function3( int c ){

printf( "You entered %d so function3 was called\n\n", c );} /* end function3 */

Enter a number between 0 and 2, 3 to end: 0You entered 0 so function1 was called

Enter a number between 0 and 2, 3 to end: 1You entered 1 so function2 was called

Enter a number between 0 and 2, 3 to end: 2You entered 2 so function3 was called

Enter a number between 0 and 2, 3 to end: 3Program execution completed.