C/C++ Generating Random Numbers in C++

Click For Summary
To randomly select a number from an array in programming, one effective method is to use the `rand()` function to generate a random index. The example provided demonstrates initializing the random number generator with `srand(time(NULL))` to ensure different results on each run. The code snippet `random = arr[rand() % (sizeof(arr) / sizeof(arr[0]))]` shows how to pick a random element from the array by calculating the index based on the array's size. This approach effectively addresses the problem of random selection from an array.
chmate
Messages
37
Reaction score
0
Hello!

I've been trying to create an algorithm which picks a number randomly from array. P.S i have an array like A={1,4,-1,3,-7,2,-14} and I want to pick a number randomly from array.

Any idea?

Thank you.
 
Technology news on Phys.org
Why don't you use rand() to draw index?
 
Hi borek, can you show me an example?

Thank you.
 
Hello!

I've solved my problem. I've been looking for this part of code:

srand(time(NULL));
random = arr[rand() % (sizeof(arr) / sizeof(arr[0]))];

Thank you.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 21 ·
Replies
21
Views
7K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
14
Views
3K
Replies
25
Views
4K
  • · Replies 2 ·
Replies
2
Views
2K
Replies
35
Views
6K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 12 ·
Replies
12
Views
3K
  • · Replies 31 ·
2
Replies
31
Views
3K
  • · Replies 9 ·
Replies
9
Views
2K