Home c Filling an array with random numbers in C

Filling an array with random numbers in C

Author

Date

Category

Studying arrays, I came to the question, how can I create an array and fill it with absolutely random values? There are resources on the Internet that provide the code for solving this problem, but unfortunately without explanation, but I would like to understand what functions are responsible for this, how many different methods there are and what are the best ways to do it so that it really is random.


Answer 1, authority 100%

If it is C++, then the standard now includes a reliable and efficient library & lt; random & gt; . If in C, then you need to use only the built-in generator rand () or write your own, relying, say, on Knuth. Of course, these are not absolutely random numbers, but pseudo-random ones.

Your question is not very precise – for example, what distribution of numbers in a matrix should be? Uniform, normal, or what else?

It usually looks like

int r [N];
for (int i = 0; i & lt; N; ++ i) r [i] = rand ();

Well, or, say, for random numbers in the range from A to B (only B-A + 1 should not exceed RAND_MAX ) –

r [i] = rand ()% (B-A + 1) + A;

If you clarify your question, it will be possible to clarify the answer 🙂

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions