Presentation is loading. Please wait.

Presentation is loading. Please wait.

Number guessing game Pick a random number between 1 and 10

Similar presentations


Presentation on theme: "Number guessing game Pick a random number between 1 and 10"— Presentation transcript:

1 Number guessing game Pick a random number between 1 and 10
Ask the user to guess a number Compare- verify that it is a number Output: You win or Try again (need a conditional loop) Hints: char someChar = '5';  int myInt = atoi(&someChar);  int isdigit(int c); Parameters c -- This is the character to be checked. Return Value This function returns nonzero value if c is a digit, else 0

2 5.9 Random Number Generation
rand function Load <stdlib.h> Returns "random" number between 0 and RAND_MAX (at least 32767) i = rand(); Pseudorandom Preset sequence of "random" numbers Same sequence for every function call Scaling To get a random number between 1 and n 1 + ( rand() % n ) rand() % n returns a number between 0 and n - 1 Add 1 to make random number between 1 and n 1 + ( rand() % 6) number between 1 and 6

3 isdigit() Function The isdigit() function is part of the character-handling library <ctype.h> #include <stdio.h> #include <ctype.h> main() { char cResponse = '\0'; printf("\nPlease enter a number: "); scanf("%c", &cResponse); if ( isdigit(cResponse) != 0 ) printf("\nThank you for entering a number\n"); else printf("\nYou did not enter a number\n"); }

4 Craps!

5 What do we need? Random number generator User input Looping
With error checking Looping

6 5.9 Random Number Generation
srand function <stdlib.h> Takes an integer seed and jumps to that location in its "random" sequence srand( seed ); srand( time( NULL ) ); //load <time.h> time( NULL ) Returns the time at which the program was executed in seconds “Randomizes" the seed

7 2 Randomizing die-rolling program */ 3 #include <stdlib.h>
1 /* Fig. 5.9: fig05_09.c 2 Randomizing die-rolling program */ 3 #include <stdlib.h> 4 #include <stdio.h> 5 6 int main() 7 { 8 int i; 9 unsigned seed; 10 11 printf( "Enter seed: " ); 12 scanf( "%u", &seed ); 13 srand( seed ); 14 15 for ( i = 1; i <= 10; i++ ) { printf( "%10d", 1 + ( rand() % 6 ) ); 17 if ( i % 5 == 0 ) printf( "\n" ); 20 } 21 22 return 0; 23 } 1. Initialize seed 2. Input value for seed 2.1 Use srand to change random sequence 2.2 Define Loop 3. Generate and output random numbers

8 Example: A Game of Chance
Craps simulator Rules Roll two dice 7 or 11 on first throw, player wins 2, 3, or 12 on first throw, player loses 4, 5, 6, 8, 9, 10 - value becomes player's "point" Player must roll his point before rolling 7 to win Prompt the user how much to bet on each throw Verify that they enter a number


Download ppt "Number guessing game Pick a random number between 1 and 10"

Similar presentations


Ads by Google