1

I have the code

char a = 97 + rand() % 26;
char b = 97 + rand() % 26;
char c = 97 + rand() % 26;
char d = 97 + rand() % 26;
char e = 97 + rand() % 26;
char f = 97 + rand() % 26;

in my program, within the main file, and when I execute the file I get the sequence lvqdyo every time, when I assumed it would randomize every time. Any insight would be appreciated, whether or not it is the answer.

Ian
  • 30,182
  • 19
  • 69
  • 107

3 Answers3

4

Initialize a random seed first using srand(). Current time can be used to do the same:

#include <cstdlib> // this is where srand() is defined
#include <ctime> // this is where time() is defined
srand (time(NULL));
char a = 97 + rand() % 26;
...

Refer this.

Such a random seed ensures that every subsequent call to rand() will produce a random number.

CinCout
  • 9,486
  • 12
  • 49
  • 67
2

To using a rand() you have to seed it first, see below example

/* rand example: guess the number */
#include <stdio.h>      /* printf, scanf, puts, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main ()
{
  int iSecret, iGuess;

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

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

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

  puts ("Congratulations!");
  return 0;
}

srand(time(NULL)) made sure the seed is starting up so the rand can works properly

Reading source : CPP - Rand()

AchmadJP
  • 893
  • 8
  • 17
1

This is because Random is not really random. It is a rather a pseudo random which depends on the seed.

For one random seed, you have one exact set of pseudo random sequence. That's why you get the same result every time you run the program because once compiled, the random seed doesn't change.

In order to make your application having random like behavior every time you run it, consider of using time info as random seed:

#include <cstdlib.h>
#include <time.h>

....
srand (time(NULL)); //somewhere in the initialization    

time(NULL) is the random seed which will change according to the system time you run your application. Then you could use your rand() with different random seed everytime:

//somewhere else after initialization
char a = 97 + rand() % 26;
char b = 97 + rand() % 26;
char c = 97 + rand() % 26;
char d = 97 + rand() % 26;
char e = 97 + rand() % 26;
char f = 97 + rand() % 26;
Ian
  • 30,182
  • 19
  • 69
  • 107