Random Numbers
eharetea

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 guessint target);
int getrand(int minint max);
void playagain(char play);

/*
*
* program
*
*/


int main ()

{

    int numtoguessuserguessnumtimes;
    char play;
    srand time(NULL) );
    

    do {
        numtoguess=getrandom(0,100);
        numtimes=0;
        printf ("Pick a number 1 through 100: ");
        do {
            if (numtimes!=0printf("Guess again:");
            guess(&userguessnumtoguess);
            numtimes++;
        } while ( (numtoguess != userguess) && ( numtimes ) );
        if (numtimes 6printf("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 guessint target)
{
    scanf ("%d",guess);
    if (target < *guessprintf ("The number is lower\n");
    else if (target > *guessprintf("The number is higher\n");
}

int getrandom(int minint 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 minint max);

/*
* program
*/

int main()
{    int i;
    srand(time(NULL));
    for (i=0i<100i++)
    {
        printf("%d\n"getrand(2,5) );
    }
    return 0;
}

/*
*
* functions
*
*/

int getrand(int minint 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
Creative Commons License
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