0

I am creating a program that prints out 1000 random occurrences of the letters "H" and "T" and my code implements rand()%2 but as i can see from running this program (code below) that its not completely random (the letters are random but always the same with every execution). I want to establish a more effective way by implementing RANDMAX to make every case of the program running completely random, how would I be able to do this?

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

int main()
{
  int i=1,n;
  char ch ;
    for( i = 1; i <= 1000 ; i ++ )
    {
     n = rand()%2;
     if(n==0)
       ch = 'T';
     else
       ch = 'H';
       putchar(ch);
     }
      return 0;
  }
dantheDude
  • 21
  • 2

1 Answers1

1

Just add

srand(time(NULL));

after

int main()
{

That will initialize the random generate with a new seed every time you run the program. In this way, you'll get a new random sequence every time.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • Note that `srand(time(NULL));` can be a very bad way to seed `rand()` for any process that's expected to be started rapidly more than once - multiple processes will wind up with the same "random" data from `rand()`. – Andrew Henle Sep 24 '19 at 20:02