Write a program to generate any one number randomly from a list of numbers.

Showing Answers 1 - 15 of 15 Answers

sharmila

  • Nov 28th, 2006
 

#include<stdlib.h>

main()

{

int a=rand();

printf("%d",a);

}

  Was this answer useful?  Yes

siriatwork

  • Dec 9th, 2006
 

I think the above code would generate a random number based on the lower and higher limits defined in the compiler, but not from a "given List". if we want to generate randomly from a list then may be we can store the list of numbers in an array and then generate the index randomly and return the particular number...

  Was this answer useful?  Yes

This prg generates a random no between the range specified in the compiler. If we want to generate a random no from a list, we can do it using array subscript. If we know the no of elements in the list, we can use % to generate a random subscript value between the specified limits. Hence using this we can select a random no from the list.

Eg.
Suppose there r 10 elements
Then,
subscipt=rand()%10 will give the required result

Now a[subscript] would be a random no from the array a.

  Was this answer useful?  Yes

NitinMishra

  • Nov 5th, 2007
 

#include

main()

{

int a=rand();

printf("%d",a);

}

The above program creates random number but this program can better be modified by using seed() function i.e combination of rand() and seed().
The number generated by the above program is not random it follows the processor instruction all the time, so the output of the above program is not really random.

  Was this answer useful?  Yes

amitprasad

  • Mar 21st, 2008
 

NitinMishra is absoulutely right that number generated by rand() is not random. I think this code will serve the purpose.....

#include <stdio.h>
#include <time.h>

int main()
{
    // Just for example, i have taken the list
    int list[10] = {12, 34, 45, 19, 54, 78, 9, 10, 99, 77};
    int random = 0;
    srand ((unsigned int)time ((time_t *)NULL));
    random = rand()% 10;
    printf ("nRandom Number(index) = %d ::NUMBER = %dn", random, list[random]);
    return 1;
}

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions