Store and print random numbers in an array in C - c

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]);
}

Related

Imprecise average at run time

I am trying to solve a problem and I've run into a bit of an issue.
I have to find the running average of a series of numbers.
Example:
input 4 2 7
output 4 3 4.3333
Now here's the problem although I get the answer, it is not the precise answer.
Accepted Output: accuracy difference shown in the image
290.6666666667
385.4000000000
487.8333333333
477.4285714286
496.4444444444
...
523.8571166992
506.0454406738
495.3043518066
I can't find whats wrong. Some help would be highly appreciated.
#include<stdio.h>
main(){
int n;
printf("set:");
scanf("%d",&n);
float arr[n+1],resarr[n+1];
float sum=0;
for(int i=1; i<=n; i++){
scanf("%f",&arr[i]);
sum=arr[i]+sum;
float res= sum/(float)i;
resarr[i]=res;
}
int i=1;
while(i<=n) {
printf("%0.10f\n",resarr[i]);
i++;
}
return 0;
}
Here
for(int i=1; i<=n; i++){ }
you are trying to access out of bound array elements, this certainly causes undefined behavior as let's assume if n is 5 then you are accessing arr[5] also which doesn't exist.
C doesn't perform array boundary condition check, its programmer responsibility to not to access out of bound elements else it causes UB.
In C array index starts from 0 not from 1. So better start rotating loop from 0 to n. For e.g
for(int i=0; i<n; i++) {
scanf("%f",&arr[i]);
/* some code */
}
Code fails to achieve the desired accuracy as it is using float rather than double. #Some programmer dude
Typical float is precise to 1 part in 223. For printing to 0.0000000001, better to use double which is typically precise to 1 part in 253.
#include<stdio.h>
int main(void) {
//float arr[n + 1], resarr[n + 1];
//float sum = 0;
double arr[n + 1], resarr[n + 1];
double sum = 0;
...
// scanf("%f", &arr[i]);
scanf("%lf", &arr[i]);
...
// float res = sum / (float) i;
double res = sum / i; // cast not needed as `sum` is `double`
...
}
Iterating from 1 is not idiomatic in C. More common to iterate starting at 0.
size_t is best for array sizing and indexing. int may be too narrow. Of course with small arrays, it makes scant difference.
#include<stdio.h>
int main(void) {
printf("set:");
size_t n;
scanf("%zu", &n);
double arr[n], resarr[n];
double sum = 0;
for (size_t i = 0; i < n; i++) {
scanf("%lf", &arr[i]);
sum = arr[i] + sum;
double res = sum / (i+1);
resarr[i] = res;
}
for (size_t i = 0; i < n; i++) {
printf("%0.10f\n", resarr[i]);
}
return 0;
}
More robust code would check the input from the user it insure it is valid, allocate rather than use a VLA if n is allowed to be large, flush output before reading, etc.
Note that array arr[] is not needed, just a single double for the input and sum.

Assigning a random value to an array

I'm trying to
Get rid of the info in an array with 10 "spots".
Fill the array with (10) random numbers
My code till time
int main()
{
int numbers[10] = { 0 };
int randNumber = 0;
int i = 0;
for (int i = 0; i <= 10; i++)
{
srand(time(NULL));
randNumber = rand() % 10 + 1;
printf("Random number saved in the array: %d\n", randNumber);
i++;
}
getchar();
getchar();
return 0;
}
First of all, you need to move the srand(time(NULL)); out of the loop.
Otherwise, because, time() has a time granularity of 1 second, in a second, if called multiple times in the loop (within a second, probably), it will re-initialize the PNRG with the same seed and all the next call to rand() will give you the same random number.
Now, once you have the random numbers, you need to assign it to the each array member like numbers[i] = randNumber; inside the loop, but there's more to it. Your loop, at present is off by one. You need to change
for (int i = 0; i <= 10; i++)
to
for (int i = 0; i < 10; i++)
to stay within bounds.
Your array's size is 10, and this loop runs 11 times, causing an overflow. This will solve it:
for (int i = 0; i < 10; i++)
Also remove the increasing of the loop's iterator, i, from inside the loop body. Remove the line:
i++;

Array of random numbers using C program

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;
}

how to pass 1000 random numbers 1-10 only, to scanf such that I can output how many of each occurance is seen?

My goal is to produce a program which can take a random number from the user (srand) and then feed it to a random number generator (rand) which then chooses 1000 iterations of a random number between 1 and 10. I then want to output how many of each number was seen (i.e. 7 appears 83 times, etc).
I'm able to printf 1000 numbers between 1 and 10 randomly after taking the initial digit from the user, but can't figure out how to take this output and feed it to an array which can then be used to break down the information for printing. Can anyone please help?
#include <stdio.h>
#include <stdlib.h>
int rand1(void);
void srand1(unsigned int seed);
int main()
{
int rand_array[1000];
int count;
int start=1;
int end=10;
int number_var;
int ones=0;
int twos=0;
int threes=0;
int fours=0;
int fives=0;
int sixes=0;
int sevens=0;
int eights=0;
int nines=0;
int tens=0;
int frequency[11];
int i=0;
unsigned seed;
printf("Please enter your choice for seed.\n");
printf("(between 1-10)");
while (scanf("%u", &seed) == 1)
{
srand1(seed);
for(i=0; i < 1000; i++)
{
rand_array[i]=rand1()%(end-start+1)+start;
frequency[rand_array[i]]++;
}
for(i = 1; i < 11; i++)
{
printf("There are %d %d's\n", frequency[i], i);
}
}
return 0;
}
int rand1(void)
{
static unsigned long int next = 1;
next = next * 1103515245 + 12345;
return (unsigned int) (next/65536) % 32768;
}
void srand1(unsigned int seed)
{
static unsigned long int next = 1;
next = seed;
}
You could have an array of size 10 (or 11), type integer, where each slot represents the number of times that number is generated. For example, slot 3 would represent the number of times you generated a 3. So try this:
//declare array to hold frequencies
int frequency[11];
//reset all slots to 0
for(int i = 1; i < 11; i++)
{
frequency[i] = 0;
}
//for each random number, increment the associated slot in the frequency array
for(int i = 0; i < 1000; i++)
{
frequency[rand_array[i]]++;
}
//print the results
for(int i = 1; i < 11; i++)
{
printf("There are %d %d's\n", frequency[i], i);
}
Note: I did not really read through most of your existing code, so I'm not sure if you have any other issues.
Edit: Here is an example of the general idea.
Say you have some random numbers:
5, 2, 4, 9, 9, 2, 1, 10
Your frequency array starts at 0s:
[0,0,0,0,0,0,0,0,0,0]
So now we loop over your random numbers, and increment the associated slot.
For example, we read the 5, now our frequency array is:
[0,0,0,0,1,0,0,0,0,0]
Then the 2:
[0,1,0,0,1,0,0,0,0,0]
Then the 4:
[0,1,0,1,1,0,0,0,0,0]
Then the 9:
[0,1,0,1,1,0,0,0,1,0]
Again
[0,1,0,1,1,0,0,0,2,0]
At the end:
[1,2,0,1,1,0,0,0,2,1]
Now we know how many of each number there are! Say we want to know how many 9's there were, we just look at the 9th slot and we see that there were 2 of them.
Does this make more sense? This is much better than having 10 separate variables for each number, and then saying "if the number was a 1, increment my 1s variable, if it was a 2, increment the 2s variable". Plus if you have, say, random numbers between 1 and 100 instead of 1-10, it will be much easier to adapt your code.

Random numbers in C

for(i = 0; i < n; i++){
srand(time(NULL));
printf("%d ", time(NULL));
for(j = 0; j < (n-1); j++){
a[i][j] = rand();
}
}
I try to generate random numbers, but they are the same... I try srand(i * time(NULL)). No matter..
What should i do?
Array declaration:
int** a;
int i;
printf("Enter array size: ");
scanf("%d", &n);
a = (int**)calloc(n, sizeof(int));
for(i = 0; i < n; i++)
a[i] = (int*)calloc(n-1, sizeof(int));
Call srand() outside of the loop. You are reseeding it every iteration.
srand() seeds the random number generator so you get a different sequence of random numbers depending on the input. Your loop runs very fast, so the call to time(NULL) always returns the same value. You are resetting to the same random sequence with every iteration. As a general rule, only call srand() once in your program.
Don't call srand() every time through the loop - just do it once beforehand.
FAQs 13.15 to 13.20 will be of interest. And I am tempted to create a new tag for such questions.
srand is a function that "seeds" the random number generator. In case you don't know, random numbers in computers aren't really random. In effect, the computer just has a list of numbers that seem random in it, and you use srand to tell it where to start in that list, with each call to rand() returning the next item in the list.
The reason you write srand(time(NULL)) is to get the random numbers to start at some point that isn't going to be the same every time you run the program (unless the programs start at the same time).
So what you are doing here is repeatedly telling the program to restart the random number list at the same point (because the time is the same each time you go through the loop). Move the call to srand outside the loop and you will get the correct results.

			
				
srand(time(NULL));
for(i = 0; i < n; i++){
printf("%d ", time(NULL));
for(j = 0; j < (n-1); j++){
a[i,j] = rand();
}
}
Call srand once outside the loop.
You need to call srand() before entering the loop. srand() initializes the radnom number generator with the given seed and generates unique sequence of random numbers for this seed.
Your loop executes very fast so every call to time(NULL) yields the same time (measured in seconds) - hence you initialize random number generator with the same seed on every loop iteration.
srand(time(NULL));
for(i = 0; i < n; i++){
for(j = 0; j < (n-1); j++){
a[i,j] = rand();
}
}
No matter. The number are the same...
int** a;
int i;
printf("Enter array size: ");
scanf("%d", &n);
if( n < 1 ){
printf("Size should be > 0\n\n");
return NULL;
}
a = (int**)calloc(n, sizeof(int));
for(i = 0; i < n; i++)
a[i] = (int*)calloc(n-1, sizeof(int));
Here is my array...
Sergey, you did not get an error message with the a[i,j] version simply because this is a perfectly valid expression. The comma operator evaluates the sub-expressions from left to right and returns the value of the last expression. Thus, writing a[i,j] is identical to a[j]. What you received in the print was the value of the pointer to the j-th vector in your matrix.

Resources