Introduction to srand() function in C and having a maximum and minimum specified as a range for random numbers.
Random numbers in C.
Date Created:Saturday March 24th, 2007 12:25 PM
Date Modified:Sunday August 03rd, 2008 11:44 AM
/*
*
*
* AUTHOR: Dan Lynch
* Synopsis: A guessing game in which a user has six chances
* to guess a number, which an option to continue playing.
*
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*
* prototypes
*/
void guess(int * guess, int target);
int getrand(int min, int max);
void playagain(char * play);
/*
*
* program
*
*/
int main ()
{
int numtoguess, userguess, numtimes;
char play;
srand ( time(NULL) );
do {
numtoguess=getrandom(0,100);
numtimes=0;
printf ("Pick a number 1 through 100: ");
do {
if (numtimes!=0) printf("Guess again:");
guess(&userguess, numtoguess);
numtimes++;
} while ( (numtoguess != userguess) && ( numtimes < 6 ) );
if (numtimes < 6) printf("You win! The number was %d!\n\n",numtoguess);
else printf("You have failed! The number was %d!\n\n",numtoguess);
playagain(&play);
} while ( play=='y' );
return 0;
}
/*
*
* functions
*
*/
void guess(int * guess, int target)
{
scanf ("%d",guess);
if (target < *guess) printf ("The number is lower\n");
else if (target > *guess) printf("The number is higher\n");
}
int getrandom(int min, int max)
{
return rand()%(max-min)+min+1;
}
void playagain(char * play)
{
printf("Would you like to play again? (Enter y for Yes, n for No)\n");
fflush(stdin);
scanf("%c",play);
}
#include <stdio.h>
/*
* prototypes
*/
int getrand(int min, int max);
/*
* program
*/
int main()
{ int i;
srand(time(NULL));
for (i=0; i<100; i++)
{
printf("%d\n", getrand(2,5) );
}
return 0;
}
/*
*
* functions
*
*/
int getrand(int min, int max)
{
return rand()%(max-min)+min+1;
}
Downloads:
Download: guess.c 1 KB
Download: rand.c 326 B
Please login or Click Here to register for downloads
Random Numbers by Dan Lynch
is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License
Based on a work at www.3daet.com
Permissions beyond the scope of this license may be available at http://www.3daet.com
