Advertisement
satyaki30

randrange C

Oct 30th, 2014
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.79 KB | None | 0 0
  1. //random number generator from 1 to n
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5. #define CHECKED 1
  6. int *flag;
  7. int* rand_range(limit)
  8. {
  9.     //random array generator
  10.     int *random_nos, i, no, ctr = 0;
  11.     random_nos = (int *) calloc(limit + 1, sizeof(int));
  12.     flag = (int *) calloc(limit + 1, sizeof(int));
  13.     srand(time(NULL));
  14.     while (ctr < limit)
  15.     {
  16.         no = rand() % limit + 1;
  17.         if (flag[no] != CHECKED)
  18.         {
  19.             flag[no] = CHECKED;
  20.             random_nos[ctr] = no;
  21.             ctr ++;
  22.         }
  23.     }
  24.     return random_nos;
  25. }
  26. void print_list(int *ar, int size)
  27. {
  28.     int i;
  29.     printf("\n");
  30.     for (i = 0; i < size; i ++)
  31.         printf("%d\t", ar[i]);
  32.     printf("\n");
  33. }
  34. int main()
  35. {
  36.     int *ar, n;
  37.     printf("\nEnter upper limit: ");
  38.     scanf("%d", &n);
  39.     ar = rand_range(n);
  40.     print_list(ar, n);
  41.     return 0;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement