Rand() not generating random variables in C - c

I've been trying to apply all advices found in this site but none seems to be working.
For the first part of the code I need to fill an array with random numbers (0 or 1) to simulate an epidemic spreading, but the array obtained is not the desired one at all... this is the code I wrote:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char **argv)
{
int N, BC, t, T, i, v[N];
float b, g, p, r;
/*Variable values initialization*/
printf("Enter infection probability:\n");
scanf("%f", &b);
printf("Enter the number of individuals:\n");
scanf("%d", &N);
printf("Enter the number of time steps:\n");
scanf("%d", &T);
printf("Periodic boundary contitions? (Y:1 / N:0)\n");
scanf("%d", &BC);
/*First set of individuals*/
srand(time(NULL));
for(i = 0; i < N; i++){
v[i] = (rand()/RAND_MAX);
}
/*Check if array properly initialized*/
printf("Initial array:\n" );
for(i = 0; i < N; i++){
printf("%d-", v[i]);
}
The outcome I expected for the array was something like: 1-0-1-1-0-0-0-..., but I always get the following one:
Initial array:
0-0-2-15-0-0-0-0-0-0-
What am I doing wrong?
Thanks a million!

You should declare v[N] after
printf("Enter the number of individuals:\n");
scanf("%d", &N);
otherwise its size will be random since N isn't initialized when the memory allocated for v[] based on N is set.
If you want just 0 or 1 you should use a modulo:
srand(time(NULL));
for(i = 0; i < N; i++){
v[i] = (rand() % 2);
}
all the even values generated by rand will become 0 and all the odd values will become 1

Related

Segmentation fault when using a 1D array

#include <stdio.h>
int main()
{
//Initialize array
int n; // n is use to decide the size of array
int x[n];
int y[n];
printf("enter the size of array:");
scanf("%d", &n);
if (n > 0)
{
for (int i = 0; i < n; i++)
{
printf("enter elements : \n");
scanf("%d", &x[i]);
}
}
printf("Array in reverse order: \n");
//Loop through the array in reverse order
for (int i = n - 1, j = 0; i >= 0; i--, j++)
{
y[j] = x[i];
printf("%d ", y[j]);
}
return 0;
}
In the above program, I have created a array whose size can be decided by the user. The user can also put elements in it.
After that I want to reverse this array and store the data in another array. But I get this error again and again. I am using CodeBlocks with the GCC compiler.
When the x and y arrays are created, n is uninitialized. There's no knowing how large these arrays will be. You loops are almost certainly accessing the array out of bounds.
You want to read n, then create the arrays. Of course you also want to error check the result of scanf.
int n; // n is use to decide the size of array
printf("enter the size of array:");
scanf("%d", &n);
int x[n];
int y[n];

C - Getting the min and max of the randomly generated numbers

My code is below, this is my first programming course so expect a possibly stupid mistake.
Basically I am trying to get the min/max and the position number of them. However, my max works correctly up until 6 numbers are generated and I can't seem to understand why.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n, r, x, i;
int max, min;
int num[0];
printf("Enter an integer");
scanf("%d", &n);
x = n;
printf("\n Pos | Val");
for(n=0; n<x; n++)
{
r = ( rand()%1000 ) + 1;
printf("\n %3d | %3d", n+1, r);
}
max=num[0];
i=0;
while(i<x) // while loop determing the biggest number
{
if(num[i]>max)
{
max=num[i];
}
i++;
}
printf("\nMax : %d",max); // biggest number
return 0;
}
There are actually several places that needs improvement in your code.
Firstly, it is invalid to declare an array of size 0 in your code int num[0];, so I'm not sure why your code work with a n up to 6.
Secondly, as you may learn very soon, indentation is very important while programming so that the code is better to understand and maintain in the future. Furthermore, while C is not a language that requires indentation (and that is considered one of its strengths) many common languages such as Python that rely on whitespace to differentiate functions do need careful management of indentation.
Third, RAND_MAX is not a multiple of 1000 so you would not obtain equal probability in your program. A srand function call is also recommended.
A possible implementation of your intended program (still ugly):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXN 1000
int main(void) {
int n, r, i;
int pos = 0;
int max;
int num[MAXN];
printf("Enter an integer");
scanf("%d", &n);
srand(time(0));
printf("\n Pos | Val");
for (i = 0; i<n; i++)
{
r = (int)(((double)rand() / (RAND_MAX + 1)) * 1000) + 1;
printf("\n %3d | %3d", i + 1, r);
num[i] = r;
}
max = num[0];
i = 0;
for (i = 1; i < n; i++)
{
if (num[i] > max)
{
max = num[i];
pos = i;
}
}
printf("\nMax : %d | Pos : %d", max, pos); // biggest number
//while (1);
return 0;
}
As far as my tests, this piece works well
As already identified by numerous answers and comments, your primary problem is your array. Standard C doesn't allow array sizes of zero. GCC does unless you tell it to complain.
However, all the other answers continue to blithely use the array. For the problem stated, there's no need for an array at all. Also, the question text mentions 'minimum' as well as 'maximum', and 'position' as well as 'value' — though the code shown reports neither minimum nor position. Clearly, if this is just a preliminary phase before using the data for some other work, then you probably do need to save the data in an array. You can then decide whether to use a C99 (or later) VLA — variable length array — or whether to use dynamic memory allocation with malloc() et al, remembering to free the allocated space with free().
Here's a simple revised program that doesn't use an array and does manage minimum and maximum as well as reporting positions. It deliberately changes the range of values to 0..999 so that there are never 4-digit numbers to throw the presentation off. You can decide what to do if you absolutely must used 1-based counting and values in the range 1..1000. (Using + 1 in selected locations is one part of the answer; deciding to replace %3d with either %d or %4d is probably the rest of the answer).
This code uses the time as a seed value for the random numbers, and it reports that seed value. If the program was going to be used seriously, I'd make it accept optional arguments, one of which would be the seed, so that previous runs can be recreated. I'd probably make it accept an argument for the number of random values to be generated too.
The code validates that a number was entered and validates that the number falls in the range 1..999, bailing out with an error message written to standard error if the value is not acceptable. Note that the error message diagnoses what is valid — there is nothing more frustrating than to be told that something is invalid but not why and what you need to do to fix it (and often, it helps to show what the program read — it might not be what the user thought the program would read).
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int n;
printf("Enter number of random values to test: ");
if (scanf("%d", &n) != 1 || n <= 0 || n >= 1000)
{
fprintf(stderr, "Didn't read a valid number in the range 1..999\n");
return 1;
}
unsigned seed = time(0);
srand(seed);
printf("Seed: %u\n", seed);
int minval = 0;
int maxval = 0;
int minidx = 0;
int maxidx = 0;
printf("\n Pos | Val\n");
for (int i = 0; i < n; i++)
{
int r = (rand() % 1000);
printf(" %3d | %3d\n", i, r);
if (i == 0)
{
minval = r;
maxval = r;
minidx = i;
maxidx = i;
}
else if (r > maxval)
{
maxval = r;
maxidx = i;
}
else if (r < minval)
{
minval = r;
minidx = i;
}
}
printf("Minimum value was %3d at index %3d\n", minval, minidx);
printf("Maximum value was %3d at index %3d\n", maxval, maxidx);
return 0;
}
Example run (program mnmx67 compiled from mnmx67.c):
$ mnmx67
Enter number of random values to test: 10
Seed: 1503763592
Pos | Val
0 | 201
1 | 216
2 | 85
3 | 793
4 | 382
5 | 780
6 | 341
7 | 661
8 | 75
9 | 266
Minimum value was 75 at index 8
Maximum value was 793 at index 3
$
You did not store your random numbers in num, also You need to have some space to store these numbers. Try this for size, i commented my changes
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int n, r, x, i;
int max, min;
int * num; // ++++++++ pointer to array
printf("Enter an integer");
scanf("%d", &n);
x = n;
num = malloc(x * sizeof(int)); // ++++++++++ allocate memory
printf("\n Pos | Val");
for(n=0; n<x; n++)
{
r = ( rand()%1000 ) + 1;
printf("\n %3d | %3d", n+1, r);
num[n] = r; // +++++++++ store your number
}
max=num[0];
i=0;
while(i<x) // while loop determing the biggest number
{
if(num[i]>max)
{
max=num[i];
}
i++;
}
printf("\nMax : %d",max); // biggest number
free(num); // +++++++++ free memory
return 0;
}
Your first mistake is that the array's dimension is zero. You need to set a size for the array.
I would do this by splitting the code into three additional functions: one to generate the numbers, and two others to find the min and max.
int *gennums(size_t n)
{
int *nums;
size_t i;
if ((nums = malloc(n * sizeof (int))) != NULL) {
for (i = 0; i < n; ++i)
nums[i] = rand() % 1000;
return nums; // caller must free
}
return NULL;
}
int min(const int *arr, size_t n)
{
assert(n > 0);
int m = arr[0];
size_t i;
for (i = 0; i < n; ++i)
if (arr[i] < m)
m = arr[i];
return m;
}
int max(const int *arr, size_t n)
{
assert(n > 0);
int m = arr[0];
size_t i;
for (i = 0; i < n; ++i)
if (arr[i] > m)
m = arr[i];
return m;
}
Here int num[0];
You are not storing your random numbers in this array.Searching in that is meaning less.
Also size of your array should be at-least equal to n

Initializes an array by a given size in random values between 1 and 500 in c

I have assignment to write program that sort an array and search for a specific number, that part I've already done, My problem is how to Initialize the array in the size that the user sets with random values ​​smaller than 500? I know how to do that with known size but not with unknown size?
example for input/output:
"Please enter the size of the array:
5"
This will help you.
int main(void)
{
int n,i;
n=rand()%500; // Get random value
int arr[n]; // Initialize the dynamic array
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
// Do your stuff
}
You can do something like this:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void printArray(int* p, int size)
{
for (int j = 0; j < size; ++ j) printf("%d ", p[j]);
printf("\n");
}
int main(void) {
srand(time(NULL)); // Start with a random seed based on time
int n = 0;
printf("Which array size do you need?\n");
if (scanf("%d", &n) != 1 || n < 1)
{
printf("Wrong input\n");
exit(0);
};
printf("Creating random array of size %d\n", n);
int* p = malloc(n * sizeof(*p)); // Reserve memory
for (int j = 0; j < n; ++j) p[j] = rand() % 500; // Generate random numbers
printArray(p, n); // Print the result
free(p); // free the allocated memory
return 0;
}

Output is the same for every number?

This program is supposed to asks the user to enter a positive integer (the integer could be of any number of digits in the range of the integer type) and replace each digit by the sum of that digit plus 6 modulus 10. The program then should swap the first digit with the last digit before it displays the output.
A sample input/output:
Enter the number of digits of the number: 5
Enter the number: 92828
Output: 48485
For some reason with my code, no matter what number I enter, everything just comes out as 6. (so if I enter 5 numbers, I get 666666). I'm new to pointers, so is there an issue with that, or do I just have some math wrong? The program runs without any compiler warnings.
#include <stdio.h>
#include <stdlib.h>
void replace(int *a, int *b, int n);
void swap(int *p, int *q);
int main()
{
int n = 0;
int i = 0;
int a[100], b[100];
//Prompt user to enter number of digits
printf("Enter the number of digits you'd like to replace: ");
scanf("%d", &n);
//Prompt user to enter the number to use
printf("Enter the number to use: ");
for(i = 0; i < n; i++);
scanf("%1d", &a[i]);
//replace function
replace(a, b, n);
for(i = 0; i < n; i++)
printf("%d", b[i]);
printf("\n\n");
return 0;
}
void replace(int *a, int *b, int n)
{
int i;
for (i = 0; i < n; i++)
{
*(b+i) = (*(a+i)+ 6) % 10;
}
printf("The output is: ");
//swap function
swap(b, (b+ (n-1)));
}
void swap(int *p, int *q)
{
int t;
t = *p;
*p = *q;
*q = t;
}
Your code is absolutely correct except a silly mistake in the following code snippet.
for(i = 0; i < n; i++);
scanf("%1d", &a[i]);
Why did you put a ; after the for statement? It means your for loop is just iterating once (instead of 5 if n = 5). As a result, only the first digit input is considered given by the user but that too be stored in a[5] (considering n = 5), values stored in a[0] to a[4] are all garbage value.
Just remove the semicolon and update your code as follows.
for(i = 0; i < n; i++)
scanf("%1d", &a[i]);
Now it works fine.
The culprit in your code is the semicolon after the for loop:
for(i = 0; i < n; i++)**;**
scanf("%1d", &a[i]);
So the scanf that you wrote is basically out of the for-loop and stores the first digit into a[n].

Recursive function calculating average from int array three by three elements

Calculating average three by three elements and replacing those elements with the average result.
Example array [1,2,7,-2,5,0, 2,8]
After transformation [3,3,3,1,1,1,5,5]
Something is wrong, I can't get it to work.
#include <stdio.h>
int main ( ) {
int n, c[n];
int *avg;
int pom=0;
printf("Enter lenght of array\n");
scanf("%d",&n);
printf("Enter elements");
for(i = 0;i < n; i++)
scanf("%d",c[i]);
avg=Average(c , n, pom);
for(i = 0; i < n; i++)
printf("Avg elements= %d",*(avg+i))
return 0;
}
int Average(int arr[], int size, int z)
{
int k, l, m, Asum;
if (size < 0) {
return arr;
} else {
k=arr[z];
l=arr[z+1];
m=arr[z+2];
Asum=(k + l + m)/3;
arr[z]=Asum;
arr[z+1]=Asum;
arr[z+2]=Asum;
}
return Average(arr,size--,z++);
}
int n, c[n]; is a problem. n is uninitialized so the size of the array is who-knows-what? This is undefined behavior.
Instead
int main(void) {
int n;
int *avg;
int pom=0;
printf("Enter length of array\n");
if (scanf("%d",&n) != 1) return -1;
int c[n];
for(i = 0;i < n; i++)
// scanf("%d",c[i]);
scanf("%d",&c[i]); // pass the address of an `int`
Likely other issues too.
Try simple input first, imagine what happens when you enter only 1 number, what will the Average function do? Don't run the code but try to execute it in your head or with pencil and paper. If you think the program only has to work with three or more numbers, try three.
A serious program would explicitly reject invalid input.

Resources