Random number generator generating the wrong set of numbers - c

I'm attempting to make a program that generates an array of random numbers where no two cells contain the same number within a given range.
Example: asking it to make an array of 4 should yield something like: 4 2 1 3, instead what I get is this: 4 2 1360726912 245694014
#include <stdio.h>
#include <time.h>
#define TRUE 1
#define FALSE 0
// generates a random number within a given range
int random(int from, int to) {
int
high = to + 1,
low = from;
return (rand() % high - low) + low;
}
// returns a random number different from any number in the array
int gen_different(int arr_len, int arr[]) {
int rand_val = random(1, arr_len);
int matches = FALSE;
for(int i = 0; i < arr_len; i++) {
if(rand_val == arr[i]) matches = TRUE;
}
if(matches) gen_different(arr_len, arr);
return rand_val;
}
// generates an array with a given number of cells, containing all different numbers
void gen_arr(int count, int arr[]) {
for(int i = 0; i < count; i++)
arr[i] = gen_different(count, arr);
}
int main() {
srand(time(NULL));
printf("Please enter an array number: ");
int num = 0;
scanf("%d", &num);
int* arr[num];
gen_arr(num, arr);
for(int i = 0; i < num; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
I get that my issue has something to do with pointers, but I'm not quite sure what I should change to make it work. Any help?

you are initializing arr[num] as
int* arr[num]; //array of pointers to integers
it should be like
int arr[num]; ////array of integers

One possible problem is you are declaring your array as a pointer to an array
int* arr[num];
this is the same as:
int ** arr;
You should actually use
int arr[num];
As you are expecting an array in your functions.

I think that:
int* arr[num];
is not what you want. Try
int arr[num];
(Note this is not legal C before C99)

Expression:
(rand() % high - low) + low
looks suspect as it is the same as rand() % high.
Did you mean:
(rand() % (high - low)) + low
?

Related

How can I create a multidimensional array of random integers printed using a function?

Baby programmer here! I am stumped. I need help with an assignment and as concluded in my last question, my professor is no help, and I have done lots of research and I cannot find any examples or answers in my book or YouTube. In C, I have to use a loop to load random integer values into a 1 dimensional array and a multidimensional array, and use functions to print the contents of each array. I've taught myself how to load random integers into a 1 dimensional array, but I'm having trouble figuring out how to call it to a function to print the results. Similarly, I can create a multidimensional array and print the results through a function, but I can't figure out how to make the integers in a multidimensional array random.
Here is what I've created and understand so far (It is a MESS and I thank you for patience in advance):
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void printArray(int a[], size_t size); //prototype
void printArray(int b[2][3]); //prototype
int main(void)
{
int n[10]; // n is an array of 10 integers
int i;
srand(time(NULL)); //uses time to make integers random
printf("One-Dimensional Array\n");
for (i = 0; i < 10; i++) //loop 10 times
{
n[i] = i + 1;
printf("%d ", (rand() % 50) + 1); //print random int from 1-100
}
printf("\nMulti-Dimensional Array\n");
int array1[2][3] = { {1, 2, 3}, {4, 5, 6} };
printArray(array1);
}
void printArray(int a[], size_t size)
{
//insert function for printing 1d array
}
void printArray(int b[][3])
{
for (size_t i = 0; i <= 1; ++i)
{
for (size_t j = 0; j <= 2; ++j)
{
printf("%d ", b[i][j]);
}
printf("\n");
}
}
Use nested loops, just like you do when printing the array.
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
array1[i][j] = rand() % 50 + 1; // random int from 1 to 50
}
}

C Methods yielding inconsistent results

Firstly I am fairly familar with Java programming and have just started to learn C programming.
Below is a program that takes inputted integers and finds the min, max and sum.
To me (at least) that code written seems logical in properly performing the needed tasks and functions.
#include <stdio.h>
#include <limits.h>
int sum(int array[], unsigned int length) {
int sumTest;
for (int i = 0; i < length; i++) {
sumTest = sumTest + array[i];
}
return sumTest;
}
int max(int array[], unsigned int length) {
int maxTest = array[0];
for (int i = 0; i < length; i++) {
if (array[i] > maxTest) {
array[i] = maxTest;
}
}
return maxTest;
}
int min(int array[], unsigned int length) {
int minTest = array[0];
for (int i = 0; i < length; i++) {
if (array[i] < minTest) {
array[i] = minTest;
}
}
return minTest;
}
int main(void) {
unsigned int length = 0;
scanf("%u", &length);
int array[length];
int temp = -1;
for (int i = 0; i < length; i++) {
scanf("%d", &temp);
array[i] = temp;
}
printf("SUM: %d\n", sum(array, length));
printf("MAX: %d\n", max(array, length));
printf("MIN: %d\n", min(array, length));
return 0;
}
However when I type in the console some entries the results vary every time.
1
10
SUM: 286271434
MAX: 10
MIN: 10
Again
1
10
SUM: -72217974
MAX: 10
MIN: 10
My compiler highlights the "<" sign in the for loops in the three methods min,max and sum telling me I am comparing unsigned and signed integers. To fix this I have tried fixing the line to look like this.
for (unsigned int i = 0; i < length; i++) {
Unfortunately I still get the same results, which logically to me makes sense as I have read that unsigned integers can hold large positive numbers. I've read a bit about C being more about memory management, is it possible that I am not considering memory as a factor. I've truth fully been looking up the syntax from handbooks and forum posts none of which don't seem to consider memory as a factor and which seems no different from java.
Can someone help me understand why this happening and what a solution is.
Thank you.
You don't ever initialize sumTest to anything before using it to keep track of the sum so the value is indeterminate. Setting it to 0 should fix the issue like so:
int sum(int array[], unsigned int length) {
int sumTest = 0;
for (int i = 0; i < length; i++) {
sumTest = sumTest + array[i];
}
return sumTest;
}
Initialize sum_test=0;.
While finding the min/max instead of saving the temp value you modify the array. This should solve it:
min_test = array[i];
As the other answers have noted, sumTest needs to be initialized to 0 before use.
You might also want to test what happens with
unsigned int length = 0;
scanf("%u", &length);
int array[length];
when you enter a very large value for length.
You have not initialized the sumTest, so it takes any garbage value. To make it more meaningful initialize it to 0
i.e. int sumTest = 0;

Sum of numbers using 2 functions

Just learning C and I'm trying to understand how I get the sum of numbers using 2 functions but the results is incorrect.
I'm trying to ask the user for 10 numbers which are stored in an array in function main. The sum is then calculated in a separate function and then displayed in main.
Here is my original code without multiple functions that works:
int main()
{
int n[10];
int index;
int sum_n = 0;
int largest_n;
int smallest_n;
int *p;
p = &n[10];
int a;
printf("Enter 10 Integers\n");
for (index = 0; index < 10; index ++){
scanf("%d", &n[index] );
sum_n += n[index];
}
printf("The Sum of numbers is %d\n", sum_n);
}
Here is me trying to convert it to functions but the sum isn't working out:
int calculations (int);
int main()
{
int n[10];
int index;
int largest_n;
int smallest_n;
int *p;
p = &n[10];
int a;
printf("Enter 10 Integers\n");
for (index = 0; index < 10; index ++){
scanf("%d", &n[index] );
}
if (n[index] = 10){
//sum_n += n[index];
printf("The Sum of numbers is %d\n",calculations(n[index]));
}
&
int calculations (int num){
int sum_n = 0;
sum_n += num;
return sum_n;
}
When I run the second program using functions for numbers 1 to 10 I'm getting:
I'm either doing something blatantly wrong or not understanding what I'm doing at all.
every time you call a function the variables declared within a function are reset.
in case you want a variable that won't be reset every time you call a function you can simply make it static.
moreover you are passing and argument n[10] but your array stores number from n[0] to n[9] . And if you want sum of all ten numbers then you have to call calculation function for every number or you could just pass whole array. here is modified code.
#include<stdio.h>
int calculations (int);
int main()
{
int n[10];
int index;
int largest_n;
int smallest_n;
int *p;
p = &n[10];
int a;
int ans=0;
printf("Enter 10 Integers\n");
for (index = 0; index < 10; index ++){
scanf("%d",&n[index]);
ans = calculations(n[index]);
}
printf("The Sum of numbers is %d\n",ans);
}
int calculations (int num){
static int sum_n;
sum_n += num;
return sum_n;
}
First you don't need array for sum in this code, Second always remember to check what returned by scanf.The code is very simple.
first part with main
int main()
{
int n;
int sum=0;
printf("Enter 10 Integers\n");
for (int index = 0; index < 10; index ++){
if(scanf("%d", &n))
sum+=n;
}
printf("The Sum of numbers is %d\n",sum);//calculations(n));
}
Second using function calculation
int sum=0;
void calculation(int num){
sum+= num;
}
int main()
{
int n;
printf("Enter 10 Integers\n");
for (int index = 0; index < 10; index ++){
if(scanf("%d", &n))
calculation(n);
}
printf("The Sum of numbers is %d\n",sum);//calculations(n));
}
Your function calculations() simply returns its parameter (0 + num is simply num).
The statement
int sum_n = 0;
in it resets sum_n to 0 every time of calling it.
Move this statement out of it - directly into main() function (and before calling calculations()).
Corrections mentioned in comments below.
int calculations (int *num){ //Should be a pointer or array eg. int num[] as you want to pass an array to this function
int sum_n = 0;
int i;
//Create loop here to iterate over array and sum elements
for(i=0; i<sizeof(num)/sizeof(int); i++)
sum_n+=num[i];
return sum_n;
}
And
if (n[index] = 10){ //This is logically incorrect. This should be if(index==10).
// n[index]=10 will assign 10 to a[10] and if will still pass as if(10) is true but make a note of it. Don't use assignment operator inside if, you need comparison operator `==`
printf("The Sum of numbers is %d\n",calculations(n[index])); //You should call calculations like this -> calculations(n). You should pass whole array not just an element.
}

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

How to count the number of times a random number between '0-6' prints in a given array?

I am trying to count the number of times a number from 0-6 appears in a given array that has values generated from a random number generator. However, my code just returns '0' instead of counting the number of times the number appears in the array. I am new to this, can someone help me?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int array[7];
int i;
int zero=0;
int one=0;
int two=0;
int three=0;
int four=0;
int five=0;
int six=0;
for (i=0; i<=7; i++)
array[i] = i;
srand( (unsigned)time( NULL ) );
for (i=0; i<=7; i++)
{
int index1 = i;
int index2 = rand()%7;
int temp;
temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
if(i==48){zero++;}
else{if(i==49){one++;}
else{if(i==50){two++;}
else{if(i==51){three++;}
else{if(i==52){four++;}
else{if(i==53){five++;}
else{if(i==54){six++;}
}}}}}}}
for (i=0; i<=7; i++){
printf("array[%d] = %d\n",i,array[i]);}
printf("Number of times each number came up is:\n");
printf("Zero:%d\n", zero);
printf("One:%d\n", one);
printf("Two:%d\n", two);
printf("Three:%d\n", three);
printf("Four:%d\n", four);
printf("Five:%d\n", five);
printf("Six:%d\n", six);
return(0);
}
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_RAND_NUMBERS (1000)
int main(void)
{
int i;
int randValue = 0;
int array[7] = {0}; // initialize array counters to 0
srand( (unsigned)time( NULL ) ); // initialize rand() function
for (i=0; i<MAX_RAND_NUMBERS; i++)
{
randValue = rand()%7;
array[randValue]++;
} // end for
printf("total number of random numbers (limited range: 0...6): %d\n", MAX_RAND_NUMBERS );
printf("Number of times each of the limited range numbers occurred is:\n");
for (i=0; i<7; i++)
{
printf("number: %d, occurrence count: %d\n",i,array[i]);
}
return(0);
} // end function: main
First of all, as mentioned above in a comment your statement :
for (i=0; i<=7; i++)
It has a error because in reality, it starts from 0 and goes all the way to 7, INCLUDING 7. That means you actually have 8 positions ( 0 -> 7) instead of (0 -> 6), which is what you desire to achieve. So it should be:
for (i=0; i < 7; i++)
That is not however the major problem. You said in your question :
I am trying to count the number of times a number from 0-6 appears in a given array that has values generated from a random number generator
In the following code :
for (i=0; i< 7; i++)
array[i] = i;`
Your array elements will not be random numbers because you assign them very determined numbers. More specifically, your array will be something like this:
[0, 1, 2, 3, 4, 5, 6].
To assign random numbers to an array I would do something like this:
srand(time(NULL));
for(i = 0; i < 7; ++i) {
array[i] = rand()%7; // this will generate numbers in the range of [0,6]
}
Ok, now you have an array of random numbers just as you wanted. So let's try to count them. I would try to implement an apparition array:
int apparition[7] = {0}; // this statement will initialize all values to 0
for(i = 0; i < 7; ++i) {
apparition[array[i]]++;
}
The code above does the following thing: it iterates over the array of numbers, and for each value it increments that specific apparition array element. Suppose you have array[i] = 6, then apparition[6] = 1, so you have counted one apparition.
Your code :
if(i==48){zero++;}
else{if(i==49){one++;}
else{if(i==50){two++;}
else{if(i==51){three++;}
else{if(i==52){four++;}
else{if(i==53){five++;}
else{if(i==54){six++;}
I suppose that you considered 48 to be the ASCII representation for 0, right?
That is not correct, because the 0 you see in that table is '0' which is actually a char value, not an integer value.
Instead you should have done
if(array[i] == 0) {zero++};
If you choose to implement the apparition array, you can print it like this:
for(i = 0; i < 7; ++) {
printf("%d appears: %d times\n", i, apparition[i]);
}
Hope it helps :-)

Resources