0

I have made a function that creates a random number between 0 and 9 but when i call the function in main in a for loop with index i = 0 ; i < n ; i++ it prints 1 random number n types. but i want different values to be printed n times. here is the code which i made :-

    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    void random_variable() {
     int i;
     srand(time(NULL));
     i = rand()%10;
     printf("%d ",i);
    }
    main() {
     for(int j=0;j<10;j++) {
      random_variable();
     }
    }

output is this :-

please click on the link to see the output :- here instead of 8 ten times i needed 10 different values

Nehal Birla
  • 142
  • 1
  • 14
  • 3
    Don't redo the `srand` inside the loop - do it once before looping. It'll cause it to get reseeded and because it can loop 10 times so quickly, it'll get reseeded to the same value each time. I won't get into the deficiencies of `rand` here. – Steve Nov 16 '17 at 18:05

2 Answers2

5

srand() initializes the PRNG (pseudo random number generator) of your standard C library. A PRNG works by applying more-or-less complicated arithmetic operations to a value stored internally and returning part of the result as the next "random" number. srand() sets this internal state.

If you call srand() every time in your function, you won't get (sensible) random numbers because the internal state is reset every time. Call it once your program starts.

2

srand() seeds your random numbers. You want to do this once, not every time.

    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    void random_variable() {
       int i;
       i = rand()%10;
       printf("%d ",i);
    }
    main() {
       srand(time(NULL));
       for(int j=0;j<10;j++) {
          random_variable();
       }
    }
ale10ander
  • 942
  • 5
  • 22
  • 42