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?
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.
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! */
you can use this to range the rand function:
rand() % (max_number + 1 - minimum_number) + minimum_number
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void gen_random_numbers(int *array, int len, int min, int max){
for (int i = 0; i < len; i++)
array[i] = rand() % (max - min + 1) + min;
}
int main() {
system("cls");
srand(time(0));
int numbers[100] = {};
gen_random_numbers(numbers, 100, 50, 70);
return 0;
}
Related
To start of, I'm using repl.it on a chromebook. I'm coding in C and I have no idea what I'm doing.
I have to generate 5 random numbers, then find the mean average of them. I already did the generating 5 random numbers by using a while loop. Now I need to find out how to find the average number. Here is the code I have so far.
int n = 1;
float mean = 0;
//create 5 random numbers
srand(time(0));
while( n <= 5)
{
dice = rand() % (100 - 1 + 1) + 1.;
printf("\n%d", dice);
n++;
}
I saw some similar questions but they where all for Python. Thank you to anyone that can help out!
This should solve your problem, or get close enough that you can take it from there:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char **argv)
{
int n = 0;
double die;
double sum = 0.0;
double mean;
//create 5 random numbers
srand(time(0));
for(int n = 0 ; n < 5 ; ++n)
{
die = rand() % (100 - 1 + 1) + 1.;
printf("%f\n", die);
sum = sum + die;
}
mean = sum / 5.0;
printf("mean = %f\n", mean);
}
onlineGDB here
So I'm just learning C and I would like to know how you could prevent a variable randomized with the rand() function from repeating the same number. I have a script which simply randomizes and prints a variable in a for loop 4 times. How could I make it so the variable never gets the same number after each time it uses the rand() function?
#include <stdio.h>
#include <stdlib.h>
int randomInt;
int main()
{
srand(time(0));
for (int i = 0; i < 4; ++i) {
randomInt = rand() % 4;
printf("%d\n", randomInt);
}
return 0;
}
On most machines, int is 32 bits. So after 232 iterations, you are sure that you'll get some repetition (and probably much before).
If you restrict yourself to much less loops, consider e.g. keeping an array of previously met random numbers (or some hash table, or some binary tree, or some other container).
For a loop repeated only 4 times, keeping an array of (at most 4-1) previously emitted numbers is quite simple, and efficient enough.
Read also about the pigeonhole principle.
A slightly different approach.
int set[] = {0, 1, 2, 3 } ;
srand(time(0));
shuffle(set,4);
using the shuffle algorithm given in this question
https://stackoverflow.com/a/6127606/9288531
I'm guessing that you are getting the same numbers because your are running your program multiple times within the same second. If time(0) hasn't changed, you will have the same seed and the same random numbers generated. Unless your program runs extremely quickly, I imagine using a seed based on microseconds instead of seconds would work:
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
int randomInt;
int main()
{
struct timeval my_microtimer;
gettimeofday(&t1, NULL);
srand(t1.tv_sec * my_microtimer.tv_usec);
for (int i = 0; i < 4; ++i) {
randomInt = rand() % 4;
printf("%d\n", randomInt);
}
return 0;
}
What you could do is keeping track of each number you already generated.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int hasMyNumberAlreadyBeenGenerated(int number, int generatedNumbers[], int size){
for(int i = 0; i < size + 1; i++){
//If you already generated the number, it should be present somewhere in your array
if(generatedNumbers[i] == number) return 1;
//If you did not, find the first available space in your array, and put the number you generated into that space
if(generatedNumbers[i] == 0){
generatedNumbers[i] = number;
break; //No need to continue to check the array
}
}
return 0;
}
int main()
{
int randomInt;
int generatedNumbers[4];
//We set "0" in all the array, to be sure that the array doesn't contain unknown datas when we create it
memset(generatedNumbers, 0x0, sizeof(generatedNumbers));
srand(time(0));
for (int i = 0; i < 4; ++i) {
randomInt = rand() % 4 + 1;
//As long as the number you generate has already been generated, generate a new one
while(hasMyNumberAlreadyBeenGenerated(randomInt, generatedNumbers, i) == 1){
randomInt = rand() % 4 + 1;
}
printf("generated : %d\n", randomInt);
}
return 0;
}
The problem with this method is that you can't generate a 0, because if you do you'll endlessly loop.
You can bypass this problem using a dynamic array using malloc() function.
If you want to write clean code you should define how many numbers you want to generate with a #define.
What you seem to be asking is a non-random set of numbers 0 to 3 in a random order. Given that;
int set[] = {0, 1, 2, 3 } ;
int remaining = sizeof(set) / sizeof(*set) ;
while( remaining != 0 )
{
int index = rand() % sizeof(set) / sizeof(*set) ;
if( set[index] > 0 )
{
printf( "%d\n", set[index] ) ;
set[index] = -1 ;
remaining-- ;
}
}
For very large sets, this approach may not be practical - the number of iterations necessary to exhaust the set is non-deterministic.
I've been trying to understand how to print out some random numbers from my own array, dont confuse this with that i want to generate random numbers into an array, which is not what im trying to accomplish.
However, my code is like this
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
srand(time(NULL));
int myarray[] = { 2, 5, 10 };
//Its here where i dont know how to use rand() in to make the program generate one random number from my array, either 2, 5 or 10. I've tried, but failed.
return 0;
}
Ive not found any similar question to this either, so would greatly appreciate some help.
int number = myarray[rand() % 3];
This generates a random number : 0 1 2 and then accesses that element from the array.
You can use the following formula to generate a random number within a range:
rnd(min, max) = (rand() % (max - min)) + min;
In your case you, min = 0 and max = 3, which gives you rand() % 3.
The other answers use rand() % 3 for generating a (pseudo-)"random" number between 0 and 2 (including both). This might work for you, but is not really random, since the numbers returned by rand() between RAND_MIN and RAND_MAX are not distributed uniformly in terms of their divisibility through a given number n (because the equivalence classes of the modulo relation have unequal amounts of members if RAND_MAX is not a multiple of n).
A better algorithm for getting (pseudo-)random numbers in a given range is:
int RangeRandom(int min, int max) {
int n = max - min + 1;
int remainder = RAND_MAX % n;
int x;
do
{
x = rand();
} while (x >= RAND_MAX - remainder);
return min + x % n;
}
You can then use the function RangeRandom as follows:
int myArray[] = { 0, 3, 5 };
printf("%d", myArray[RangeRandom(0, 2)]);
I am using the random() function, and I was wondering if there is a reason that I'm always getting 8-10 digit numbers. I just want to make sure there isn't something wrong with my program. Thanks.
Here's the function:
void random_array(int* p, int size) {
/*seed random number generator */
srandom(time(NULL));
int i;
for(i = 0; i < size; i++)
*(p+i) = random();
}
Well, mathematically the chance that you will get a big number is a lot more than the chance for a (relatively) small one. For instance, if you pick a random number with (1-4) digits, the chance that it would be in the range (0-99) would be only 1 %.
With that said, if you want smaller numbers, you can take the random modulo some certain number:
a = random() % 100; // this will give you a random number from 0 to 99
b = 10 + random() % 15; // random number from 10 to 24
Number of 8-10 digits numbers: 10,000,000,000 - 100,000,000 = 9,900,000,000 (9.9 billion)
Number of 0-7 digit numbers: 10,000,000 (10 million)
In other words, there are 990 8-10 digit numbers for every 1 0-7 digit number. Therefore, you can expect to get about 1 0-7 digit number for every 990 8-10 digit numbers.
Put simply, it's because there are more of them.
How large a number were you expecting to receive from random()?
If you want to limit the size of the number generated, simply use a modulus operator to limit the result to the remainder (in the example below a number from 0 to 999):
*(p+i) = random() % 1000;
Mathematically it is likely since big numbers are..well.. more than small ones, so yes. It is much more likely to get such a number.
To generate a custom-interval random number use something like
http://ideone.com/bWbBgJ
#include <stdlib.h>
#include <stdio.h>
// Generate random numbers in the min-max interval
void random_array(int* p, int size, int min, int max) {
/*seed random number generator */
srandom(time(NULL));
int i;
for(i = 0; i < size; i++)
*(p+i) = (random() % max) + min;
}
int main(void) {
int array[3];
random_array(array, 3, 0, 12);
printf("%d\n", array[0]);
printf("%d\n", array[1]);
printf("%d\n", array[2]);
return 0;
}
I need to store random numbers between 500 and 600 to an array using a pointer and then print out those numbers. I get a segmentation error...core dump, I don't really understand what that means. The error happens after the printf statement ("%15d\n", aPtr[i]);
int main(){
int size;
int j, i;
int temp;
int sum = 0;
printf("Enter size of array");
scanf("%d", &size);
int array[size];
int *aPtr = malloc(sizeof(int) * size);
for (i = 0; i <= size; i++){
srand(time(NULL));
aPtr[i] = rand() % 500 + 100;
printf("%15d\n", aPtr[i]);
i <= size; should be i < size;
If you have an array of 50 items, the valid indices are [0,49].
you need to call srand ( which initializes the random number generator ) only once. Move it out of the for. And if you want random numbers between 500 and 600, you need to generate them between 0 and and 100 ( rand() % 101) and then add 500.
You need to call srand before you enter the loop.
As it stands now, you'll get a long sequence of identical numbers because you're resetting the random number generator to the same seed each time (assuming the time doesn't change, which is likely). In addition, if you want numbers between 500 and 600 inclusive, your formula is wrong. Try this snippet:
srand(time(NULL));
for (i = 0; i < size; i++){
aPtr[i] = (rand() % 101) + 500;
printf("%d\n", aPtr[i]);
}