Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generate a random number between 1 and 10 in c

Tags:

c

random

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

int main()

{
    int randomnumber;
    randomnumber = rand() % 10;
    printf("%d\n", randomnumber);
    return 0;
}

This is a simple program where randomnumber is an uninitialized int variable that is meant to be printed as a random number between 1 and 10. However, it always prints the same number whenever I run over and over again. Can somebody please help and tell me why this is happening? Thank you.

like image 892
Nisarg Avatar asked Jul 24 '13 22:07

Nisarg


People also ask

How do you generate a random number between 1 and 6 in C?

And the rand () function is called with module 10 operator to generate the random numbers between 1 to 10. srand(time(0)); // Initialize random number generator. srand(time(0)); // Initialize random number generator.


1 Answers

You need a different seed at every execution.

You can start to call at the beginning of your program:

srand(time(NULL));

Note that % 10 yields a result from 0 to 9 and not from 1 to 10: just add 1 to your % expression to get 1 to 10.

like image 115
ouah Avatar answered Sep 20 '22 16:09

ouah