Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random number in while loop [C programming] [duplicate]

Tags:

c

loops

random

I'm trying to create 2 random numbers (between 0-4 and 0-10) in each time the cycle occurs, but it always give the same number. If I run the program multiple times, it gives different numbers, but the while cycle always generates the same 2 numbers. thanks.

int random(int range){
    int num;
    srand(time(NULL));
    num = rand() % range;
    return num;
}

int main(){

    int cnt = 0;
    int i;  
    int j;
    while (cnt <= 20) {
        i = random(5);
        j = random(10);
        printf("%d\n",i);
        printf("%d\n",j);
        printf("\n");
        cnt += 1;
    }
    return 0;
}
like image 822
Pedro Avatar asked Feb 11 '26 14:02

Pedro


2 Answers

You only need to seed the random number generator once.

So run this line outside of your random function:

srand(time(NULL));

.. in your main function instead:

int random(int range){
    int num;
    num = rand() % range;
    return num;
}

int main(){
    int cnt = 0;
    int i;    
    int j;

    // Seed random number generator
    srand(time(NULL));

    while (cnt <= 20){
        i = random(5);
        j = random(10);
        printf("%d\n",i);
        printf("%d\n",j);
        printf("\n");
        cnt += 1;
    }
    return 0;
}
like image 168
bwegs Avatar answered Feb 13 '26 16:02

bwegs


You require to seed the random function just once. Include the time.h library and use

#include<time.h>
.....
srand(time(NULL));
like image 28
Raghav Somani Avatar answered Feb 13 '26 14:02

Raghav Somani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!