This question already has answers here:
random element from array in c
(5 answers)
Closed 2 years ago.
Basically i made an array with number 1,2,3.
int array[3] = {1,2,3};
How can I select a random number from this list and assign it to a different variable?
Use the rand() function and mod the result down to 3 values 0, 1, or 2 using mod. Then access the corresponding value in your array:
srand(time(NULL));// without this rand() function might continuously give the same value
int index = rand() % 3;
printf("random: %d\n", array[index]);
Considering that the array contains hardcoded values, you could simply:
int i = (rand() % 3) + 1;
printf("random: %d\m", i);
Include the header file <stdio.h>, <time.h>, <stdlib.h>
Related
This question already has answers here:
What does the comma operator , do?
(8 answers)
Closed 6 months ago.
How can an array have an index like [0,1,2]?
And why is [0,1,2]=[2]
Code:
int main(){
int a[]={1,2,3,4,5};
a[0,1,2]=10;
for(int i=0;i<5;i++)
printf("%d ",a[i]);
return 0;
}
Output:
1 2 10 4 5
The comma operator (,) evaluates both expressions and returns the second one (see, e.g., this explanation). I.e., 0,1,2 will evaluate to 2, so a[0,1,2]=10 will result in a[2]=10, which explains the output you get.
a[0,1,2] will be treated as a[2] aka the other indices are ignored.
To test this try: printf("%d ",a[0,1,2]); you will see it prints the
value in index 2 only.
To change the values of multiple indices then you either do it
manually or iterate over them. For example,
a[0] = 10;
a[1] = 10;
a[2]=10;
OR
for(int i = 0; i < 3; i++)
a[i]=10;
This question already has answers here:
How do I determine the size of my array in C?
(24 answers)
random number in while loop [C programming] [duplicate]
(2 answers)
How can one print a size_t variable portably using the printf family?
(14 answers)
Closed 2 years ago.
I'm writing a program in C to add random numbers to an array. The size of the array is given (say n = 250) and using rand(), I'm generating these numbers (range is 1 to 100).
int main()
{
int n = 250;
int array[n];
for (int i = 0; i < n; i++)
{
srand(time(NULL));
int r = rand()%100 + 1;
array[i] = r;
}
printf("Output Size: %lu\n", sizeof(array));
return 0;
}
When I run the code, the result is-
Output Size: 1000
Expected result is 250. What am I doing wrong?
I think you're expecting n as output (number of elements in the array); but you're doing it wrong. Currently, what you're getting is 250*4 = 1000 (i.e., size of int is 4, and the number of elements is 250).
Replace sizeof(array) with sizeof(array)/sizeof (array[0])
Read this to dive deeper.
sizeof(type) returns the size, in bytes, of the type.
To find out size of array, you can do:
printf("Output Size: %zu\n", sizeof(array)/sizeof(array[0]);
Also, the type of the result of sizeof operator is size_t. You should use %zu format specifier instead of %lu.
You have 250 elements array, each array element is of size 4 bytes.
250*4 = 1000.
And you don't need to call srand in loop.
read this article about srand.
This question already has answers here:
Why do I always get the same sequence of random numbers with rand()?
(12 answers)
If I don't specify srand(), what seed does rand() use?
(5 answers)
Closed 5 years ago.
Program uses rand() function to generate random index. But it always produces same string no matter what! Why won't this work?
void rand_string()
{
int a[10];
int i;
char b[] = "qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM";
printf("%d", sizeof(b) / sizeof(b[0]));
for(i = 0; i < 10; i++)
{
int gen_rand = rand() % 63;
a[i] = b[gen_rand];
}
for(i = 0; i < 10; i++)
printf("%c", a[i]);
}
Use srand function to seed the random generator
srand((unsigned)time(NULL));
Note that you only have to seed once in your program otherwise it will not work properly.
You could firstly define a random function specific to your needs, i.e. generating in specific range (the length of the current string), like so:
int random(int min, int max)
{
return min + (rand()) / (RAND_MAX / (max - min));
}
then in your string-random-generator function you could also add a random length to every string:
void rand_str()
{
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"; // define only on first call
// call srand() using #include <time.h> ; could be outside of function, i.e. in main()
int length = random(0, 10); // get random length in [0, 10] on each call
// use length and random(0, sizeof(alphanum) / sizeof(alphanum[0])) in for loop
// everything else is the same...
}
use the keyword static to indicate single1 definition of the array alphanum (think of it that it is like making it global) and call function srand() once, before the use of random().
Note: you should consider modifying your function to a single purpose, i.e. only generating a random string and returning (a pointer to) a string; and printing it in a separate function.
1. Only on the first call of rand_str().
This question already has answers here:
Generate random number in C within a range and a specific step
(2 answers)
How to use the rand function to make numbers in a specific range?
(4 answers)
Closed 5 years ago.
I've tried but it doesn't seem to give me the desired numbers. Here's my code so far:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i;
printf("Value of n:\n");
scanf("%d", &n);
int t[n];
for(i=0; i<n; i++)
printf("%d ", rand()%20+30);
return 0;
}
printf("%d ", rand()%20+30);
generates random numbers between 30 and 50 (not included). You need
printf("%d ", rand()%10+20);
to generate between 20 and 30 (not included)
10 being the range, and 20 being the offset.
To include both end points (giving 11 possible values):
printf("%d ", rand()%11+20);
these are the expressions
number = 21 + rand() % 9 // for (20, 30)
number = 20 + rand() % 11 // for [20, 30]
Try rand()%10+20.
rand()%10 gives numbers between 0 and 9. Adding then 20 will give numbers between 20and 29.
For numbers between 20 and 30 (inclusive), use rand()%11+20.
To generate random number in range [A .. B], first take difference between numbers: D = B-A, then generate a random number in the range of [0..D] and add that to A:
unsigned myRand(unsigned fromA, unsigned toB)
{
if (fromA > toB) // check if fromA is
return myRand(toB, fromA);
int d = toB - fromA; // difference between numbers: D = B-A
int r = rand() % (d+1); // random number in the range of [0..D]
return r + fromA;
}
Or, you may just to it manually like this:
20 + (rand()%11)
Also, note that depending on implementation rand() returns values between 0 and RAND_MAX, so you won't be able to create random values large than RAND_MAX (which might be as small as 32767). In this cases you may combine multiple rand() calls to get large random numbers:
unsigned r = (rand() << 16) | rand();
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
In C, how do I get a specific range of numbers from rand()?
Generate a random number within range?
I'm stuck on how to use the rand() function and include a range for that random number. I need a random number between 67.00 and 99.99 only to be printed.
This is what I have tried, but failed with...
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int x = rand();
if(x>=67.00)
if(x<=99.99)
printf("%d\n",x);
else
printf("not in range");
}
Instead of checking if the result is in the range, you can force the result to be in the range that you want:
int HIGH = 100;
int LOW = 67;
int rnd = LOW + (rand() % (HIGH-LOW));
The value of rnd is in the range between LOW and HIGH-1, inclusive.
If you do not want to force the number into range, change your condition to
if(x>=67.00 && x<=99.99)
Currently, the else belongs to the inner if, so the second printf does not happen when the number is less than 67.