Random Number & How to limit Random Number in C

We can create random numbers with the help of library function rand(). This library function is included in the header file stdlib.h . This will generate random numbers each time. For example you may look through this code:

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

int main()
{
    int a,b,c;
    a = rand();
    b = rand();
    c = rand();
    printf("a = %d\nb = %d\nc = %d",a,b,c);
    return 0;
}


Run the program. You will see three randomly generated numbers are printed on the screen. In my case I got the following values:

a = 41
b = 18461
c = 6334

Run the program again. You will see the same result again. So you might want to change the random number every time you want to run your program. To do so, add srand(time(NULL)) before the assignment of the random numbers to the variables. This requires to include time.h header file. So the above example will be:

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

int main()
{
    int a,b,c;
    srand(time(NULL));
    a = rand();
    b = rand();
    c = rand();
    printf("a = %d\nb = %d\nc = %d",a,b,c);
    return 0;
}

Now run the program. You will see randomly generated numbers each time. J

How to limit Random Number:


Now, you may want to limit the random number. You can do this using the modules (%) operator.

Range
How To
0 to 9
rand() % 10
1 to 10
rand() % 10 + 1
0 to 99
rand() % 100
1 to 100
rand() % 100 + 1

To see an example I am sharing code of a guess number game. Here is the program:

/* rand example: guess the number */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>      

int main ()
{
  int secret, guess;

  /* initialize random seed: */
  srand (time(NULL));

  /* generate secret number between 1 and 10: */
  secret = rand() % 10 + 1;

  do {
    printf ("Guess the number (1 to 10): ");
    scanf ("%d",&guess);
    if (secret<guess) puts ("The secret number is lower");
    else if (secret>guess) puts ("The secret number is higher");
  } while (secret!=guess);

  puts ("Congratulations! Thats The right Answer!");
  return 0;
}

I hope you have understood what happened here.

0 comments :

Post a Comment

Spam comments will be deleted. :)

 
Loading...
TOP