Hey actually when we are usin the random function we generally tend to take
all the no.s
eg.random(5)
012345

but i wanted to take random from only a few no.s like 3 5 7 5 9 and not ny other numbers..
cud neone help me

Recommended Answers

All 2 Replies

You can use an array of allowable outcomes/numbers, and use the rand() function (limited appropriately) to index one of the set. e.g. ::

int myRandFn(){
  const int allowedNumbers[] = {3, 5, 7, 9};
  return allowedNumbers[rand() % sizeof(allowedNumbers)];
  }

Or you can use an equation to get what you want. in your example you specify 3,5,7,9 so:

n = rand() % 4;   // get numbers 0,1,2,3
n *= 2;           // make them now 0,2,4,6
n += 3;           // offset them to 3,5,7,9
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.