hi all, i am new to iPhone Programing i have 10 number say (1,2,3,4,5,6,7,8,9,10) i want to choose randomly 1 number from above 10 number.so how can i choose random number from a set of numbers
To generate a random number you should use random() function. But if you call it twice it gives you two equal answers. Before calling random(), call srand(time()) to get fresh new random number. if you want to use for(int i = 0; ...) to create numbers, use srand(time() + i).
something like this
- (IBAction)generate:(id)sender { // Generate a number between 1 and 10 inclusive int generated; generated = (random() % 10) + 1;
}
If you simply want a value between 1 and 10, you can use the standard C rand()
method. This returns an integer between zero and RAND_MAX.
To get a value between 0 and 9 you can use the %
operator. So to get a value between 1 and 10 you can use:
rand()%10 + 1
If you don't want the same series of pseudo random numbers each time, you'll need to use srand
to seed the random number generator. A good value to seed it with would be the current time.
If you're asking about choosing a number from a list of arbitrary (and possibly non consecutive) numbers, you could use the following.
int numbers[] = {2,3,5,7,11,13,17,19,23,29};
int randomChoice = numbers[rand()%10];