I observed that rand()
library function when it is called just once within a loop, it almost always produces positive numbers.
for (i = 0; i <
To avoid 0, try this:
int rnumb = rand()%(INT_MAX-1)+1;
You need to include limits.h
.
May be you could try rather a tricky approach by ensuring that the value returned by sum of 2 rand() never exceeds the value of RAND_MAX. A possible approach could be sum = rand()/2 + rand()/2; This would ensure that for a 16 bit compiler with RAND_MAX value of 32767 even if both rand happens to return 32767, even then (32767/2 = 16383) 16383+16383 = 32766, thus would not result in negative sum.
rand()
is defined to return an integer between 0
and RAND_MAX
.
rand() + rand()
could overflow. What you observe is likely a result of undefined behaviour caused by integer overflow.