C - Generating Pseudo-Random Integers

Introduction

rand() function declared in the stdlib.h header file returns random numbers.

int chosen = 0;
chosen = rand();  // Set to a random integer

Each time you call the rand() function, it will return a random integer.

The value will be from zero to a maximum of RAND_MAX, the value of which is defined in stdlib.h.

The integers generated by the rand() function are described as pseudo-random numbers.

The sequence of numbers generated by the rand() function uses a starting seed number.

For a given seed the sequence will always be the same.

To get a different sequence of pseudo-random numbers each time a program is run, you can use the following statements:

srand(time(NULL));                // Use clock value as starting seed
int chosen = 0;
chosen = rand();                  // Set to a random integer 0 to RAND_MAX

You only need to call srand() once in a program to initialize the sequence.

Each time you call rand() subsequently, you'll get another pseudo-random number.

To obtaining values in a range:

srand(time(NULL));                // Use clock value as starting seed
int limit = 20;                   // Upper limit for pseudo-random values
int chosen = 0;
chosen = rand() % limit;          // 0 to limit-1 inclusive

To get numbers from 1 to limit, you can write this:

chosen = 1 + rand() % limit;      // 1 to limit   inclusive

The following code shows how to let user guess a random number.

Demo

#include <stdio.h>
#include <stdlib.h>               // For rand() and srand()
#include <time.h>                 // For time() function

int main(void)
{
  int chosen = 0;                 // The lucky number
  int guess = 0;                  // Stores a guess
  int count = 3;                  // The maximum number of tries
  int limit = 20;                 // Upper limit for pseudo-random values

  srand(time(NULL));              // Use clock value as starting seed
  chosen = 1 + rand() % limit;    // Random int 1 to limit

  printf("\nThis is a guessing game.");
  printf("\nI have chosen a number between 1 and 20"
    " which you must guess.\n");

  for (; count > 0; --count)
  {//from   w  w w  . j a v  a 2  s. c o  m
    printf("\nYou have %d tr%s left.", count, count == 1 ? "y" : "ies");
    printf("\nEnter a guess: ");  // Prompt for a guess
    scanf("%d", &guess);          // Read in a guess
                    // Check for a correct guess
    if (guess == chosen)
    {
      printf("\nCongratulations. You guessed it!\n");
      return 0;                       // End the program
    }
    else if (guess < 1 || guess > 20)  // Check for an invalid guess
      printf("I said the number is between 1 and 20.\n ");
    else
      printf("Sorry, %d is wrong. My number is %s than that.\n",
        guess, chosen > guess ? "greater" : "less");
  }
  printf("\nYou have had three tries and failed. The number was %ld\n",
    chosen);
  return 0;
}

Result

Related Topic