[c] generate a random number between 1 and 10 in c

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

int main()

{
    int randomnumber;
    randomnumber = rand() % 10;
    printf("%d\n", randomnumber);
    return 0;
}

This is a simple program where randomnumber is an uninitialized int variable that is meant to be printed as a random number between 1 and 10. However, it always prints the same number whenever I run over and over again. Can somebody please help and tell me why this is happening? Thank you.

This question is related to c random

The answer is


Here is a ready to run source code for random number generator using c taken from this site: http://www.random-number.com/random-number-c/ . The implementation here is more general (a function that gets 3 parameters: min,max and number of random numbers to generate)

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

// the random function
void RandomNumberGenerator(const int nMin, const int nMax, const int  nNumOfNumsToGenerate)
{
  int nRandonNumber = 0;
  for (int i = 0; i < nNumOfNumsToGenerate; i++)
  {
    nRandonNumber = rand()%(nMax-nMin) + nMin;
    printf("%d ", nRandonNumber);
  }
  printf("\n");
}

void main()
{
  srand(time(NULL));
  RandomNumberGenerator(1,70,5);
}

You need to seed the random number generator, from man 3 rand

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

and

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

e.g.

srand(time(NULL));

Generating a single random number in a program is problematic. Random number generators are only "random" in the sense that repeated invocations produce numbers from a given probability distribution.

Seeding the RNG won't help, especially if you just seed it from a low-resolution timer. You'll just get numbers that are a hash function of the time, and if you call the program often, they may not change often. You might improve a little bit by using srand(time(NULL) + getpid()) (_getpid() on Windows), but that still won't be random.

The ONLY way to get numbers that are random across multiple invocations of a program is to get them from outside the program. That means using a system service such as /dev/random (Linux) or CryptGenRandom() (Windows), or from a service like random.org.


srand(time(NULL));

int nRandonNumber = rand()%((nMax+1)-nMin) + nMin;
printf("%d\n",nRandonNumber);