# generating random words

Show 80 post(s) from this thread on one page
Page 2 of 2 First 12
• 07-21-2006
Wraithan
It would be used for the same thing you are doing... I have also used it when reading in binary data so that I could check the number before trying to change it to a char.
• 07-21-2006
lilrayray
oh ok. This is one of the reasons i started to teach myself C. There are so many ways to do things that you are not bound to rigid inflexibility.
• 07-23-2006
taher84
something i would like to add to add abt srand is that using srand and subsequently using rand gives you any random no upto RAND_MAX defined in stdlib(not sure check it out for urself).....so if u want to generate and random no from 1 to 26 do the operation 26*rand()/RAND_MAX and read it as int...before that add 0.5 to the no for rounding off else u would always miss 26 hence 'z'....use this random no to access ur array to generate random alphabets
If that was of any little help
• 07-23-2006
Dave_Sinkula
taher84, you need to read this.
• 07-23-2006
taher84
SURELY...i would give a reading to it...thanks for it..anyway i would like to know if there is some anomaly with my method coz i have been successfully using it
• 07-23-2006
Dave_Sinkula
Quote:

26*rand()/RAND_MAX
If RAND_MAX is the same as INT_MAX and rand returns a value close to RAND_MAX and you multiply it by 26 you've just overflowed the int range. Oops. Bad.
• 07-23-2006
taher84
i guess then (rand()/RAND_MAX)*26 should do the trick.....hehe....game of precedence
• 07-23-2006
Desolation
Code:

```char* random_word(int n) {   char* array = (char*)malloc(sizeof(char) * (n + 1));   for(int i = 0; i < n; i++)     /* 96 corresponds to 'a' ASCII */     array[i] = (rand() % 96) + 26;   return array; }```
This simple. Note that you are responsible of freeing up the memory allocated and also to call srand().
• 07-23-2006
taher84
mr desolation you are again missing the point that rand()%N never gives you a sufficient randomization its because the lower bits are not that random(refer to the tute above)
• 07-24-2006
Dave_Sinkula
Quote:

Originally Posted by taher84
i guess then (rand()/RAND_MAX)*26 should do the trick.....hehe....game of precedence

That's a long way to write zero (well almost always zero).
Show 80 post(s) from this thread on one page
Page 2 of 2 First 12