-2

I am writing a basic crypto program using c language. In that i want to get a random numbers form certain range say (97 to 122). I saw this program on some programming website.

int main(void) 
{
  int c, n;

  printf("Ten random numbers in [1,100]\n");

  for (c = 1; c <= 10; c++) 
  {
    n = rand() % 100;
    printf("%d\n", n);
  }

}

but it prints random values from 1 to 100. In python we implement it with the help of rand() function eg: r = random.randint(97, 122). so is there any way to implement like this in c program.

pkarthicbz
  • 93
  • 2
  • 10
  • 1
    Yes. The simplest way, **and wrong**, would be to write `97 + rand()%(122-97)`. For learning purposes this is enough. For serious crypto [the first rule of serious crypto is "do not roll your own"] you want a function with flat distribution, which *modulo lowercase range* is not. – LSerni Apr 10 '17 at 15:58
  • 1
    `rand()` is not cryptographically secure. Read from /dev/urandom, use something like `arc4random`, or read from a truly random source. – midor Apr 10 '17 at 15:59
  • @LSerni I just get into crypto and thankyou i keep that in my mind. – pkarthicbz Apr 10 '17 at 16:09
  • By the way, rand()%N will return numbers from 0 to N *excluded*, so the formula in my comment, above, will never return 'z'. You need to add 1 to get the full range – LSerni Apr 10 '17 at 16:30

2 Answers2

0

Figure out how many numbers are between 97 and 122 (hint -- watch out for the off-by-one error), pick a random number between 0 and x, and then add 97 to it.

hymie
  • 1,982
  • 1
  • 13
  • 18
0
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

int main()
{
  int n = 0;
  srand(time(NULL)); // seed for rand

  for (int c = 1; c <= 10; c++)
   {
     n = rand() % 25 + 97; // rand() gives you a number between 0 and 24 and then add 98 to get a number between 97 and 122
     printf("%d\n", n);
   }
}
RomMer
  • 909
  • 1
  • 8
  • 19