Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of random numbers using C program

Tags:

c

Im new to C program and I am required create 100 random numbers between 50 and 70, and store them in an array of double. How do I start?

like image 872
user3381419 Avatar asked Dec 04 '22 07:12

user3381419


2 Answers

Create an array:

int my_array[100];

Seed the random number generator

srand(0);

Loop over your array and fill it up!:

int i;
for (i = 0; i < 100; i++) {
    my_array[i] = rand();
}

That's a start. However, the range of rand() is much larger than the range of random numbers you want. There are many ways to narrow the range. If you don't care about the numbers being perfectly random, you can use the modulo operator, where 13 % 10 = 3.

This is for ints. I want to leave some fun for the reader.

like image 180
Scott Lawrence Avatar answered Dec 23 '22 17:12

Scott Lawrence


If the number is between 50 and 70, then I would say, try modulo and the rand() function of c. So firstly since you will want yo use random numbers, I would advice including the standard library. Do:

#include <stdlib.h>`

double bal[100];

for (int f = 0; f < 100 ;f++) {
    bal[f] = (rand() % 20) + 50;
}

The reason why I modulo 20 is because the difference between 50 and 70 is 20 so, if you assume 50 is zero then 70 will be 20 and so any number we will produce will be between these numbers. Hope it helps! */

like image 20
Mohamed Mnete Avatar answered Dec 23 '22 15:12

Mohamed Mnete