Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I avoid printing duplicate numbers? [C language]

output

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

int randint(void);

int main(void) {
    for (int i = 0; i < 10; i++) {
        printf("%d ", randint());
    }

    return 0;
}

int randint(void) {
    srand((unsigned)time(NULL));

    return rand() % 81 + 10;
}

My intention is to print 10 different numbers. However, 10 duplicate numbers are printed continuously each time. How can I resolve this issue?

I used library functions like the srand() function. And I changed the position of the function little by little, but the result was the same.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Expected
84 40 35 60 45 84 40 77 37 11

Output
11 11 11 11 11 11 11 11 11 11

>Solution :

The call to the srand() routine ought to occur only once, in such a use case as yours at least, though in many cases that’s the norm. For further reading you can refer to this question: How does calling srand more than once affect the quality of randomness?

By placing it within the routine, you’re invoking it every time, thus constantly altering your seed, which in this case it but resets it, therefore producing identical values for each invocation.

To get rid of this unwanted behaviour you ought to place srand() within the main function, or at least at a location that’s both prior to the call to rand(), and outside a loop, or other structure which will get invoked repeatedly, such as your function.

Here’s a revised version of your code:

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

int randint(void);

int main(void) {
    srand((unsigned)time(NULL));

    for (int i = 0; i < 10; i++) {
        printf("%d ", randint());
    }

    return 0;
}

int randint(void) {
    return rand() % 81 + 10;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading