Populate and print array with random numbers using C - c

I'm trying to write a program that will populate an array of 100 elements with numbers between 1 and 22, and then print the array in a 20 x 5 table. I was able to populate the array and print it, but can only get it to work with numbers 1-100, how can I change it to only do numbers 1-22?
#include <stdio.h>
#include <stdlib.h>
#define ARY_SIZE 100
void random (int randNos[]);
void printArray (int data[], int size, int lineSize);
int main(void)
{
int randNos [ARY_SIZE];
random(randNos);
printArray(randNos, ARY_SIZE, 20);
return 0;
}
void random (int randNos[])
{
int oneRandNo;
int haveRand[ARY_SIZE] = {0};
for (int i = 0; i < ARY_SIZE; i++)
{
do
{
oneRandNo = rand() % ARY_SIZE;
} while (haveRand[oneRandNo] == 1);
haveRand[oneRandNo] = 1;
randNos[i] = oneRandNo;
}
return;
}
void printArray (int data[], int size, int lineSize)
{
int numPrinted = 0;
printf("\n");
for (int i = 0; i < size; i++)
{
numPrinted++;
printf("%2d ", data[i]);
if (numPrinted >= lineSize)
{
printf("\n");
numPrinted = 0;
}
}
printf("\n");
return;
}

#Sarah Simply include time.h header file (from the standard library), then rewrite your random function as follow:
void Random(int RandNos[])
{
/*
Since your random numbers are between 1 and 22, they correspond to the remainder of
unsigned integers divided by 22 (which lie between 0 and 21) plus 1, to have the
desired range of numbers.
*/
int oneRandNo;
// Here, we seed the random generator in order to make the random number truly "random".
srand((unsigned)time(NULL));
for(int i=0; i < ARY_SIZE; i++)
{
oneRandNo = ((unsigned )random() % 22 + 1);
randNos[i] = oneRandNo; // We record the generate random number
}
}
Note: You are asked to include time.h in order to use the time() function. If you are
working under Linux Or Mac OSX, you can find more information about this function by
type the command man 3 time in the terminal to easily access the documentation.
Also, naming your function random will conflict with that of the standard library. That is why I use Random instead.

Related

how to create an array of random number, all different from each other?

The program should just print out the elements of the array, which stores random integers between 10 and 30. I wanted the numbers to be different from each other, but my program isn't working, what is wrong with it? thanks
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
const int N=12;
int arr[N],i,j;
srand(time(0));
for(i=0; i<N; i++)
arr[i]=10+rand()%20;
for(i=0; i<N; i++)
{
for(j=N-1; j == 0; j--)
{
do
{
arr[i]=10+rand()%20;
if(arr[i]!=arr[j])
break;
}
while(arr[i]==arr[j]);
}
printf(">>%d\n",arr[i]);
}
return 0;
}
The fact that the numbers need to be different from one another means that they are not truly random. You can create another set of numbers with elements 10 through 30 in them. Randomize that list and pull them into your array.
C++ version:
const int begin = 10;
const int end = 30;
// creates a vector of 30-10 zeroes
std::vector<int> v(begin-end);
// fill vector with 10, 11, ..., 30.
std::iota (std::begin(v), std::end(v), begin);
// a source for random seed
std::random_device rd;
// seed this generator with 32-bit number
std::mt19937 g(rd());
// randomly shuffle a vector
std::shuffle(std::begin(v), std::end(v), g);
const int N = 12;
std::vector<int> result(v.begin(), v.begin() + N);
C version:
#include <stdio.h>
#include <stdlib.h>
// https://stackoverflow.com/a/6127606/1953079
void shuffle(int *array, size_t n)
{
if (n <= 1) { return; }
size_t i;
for (i = 0; i < n - 1; i++)
{
size_t j = i + rand() / (RAND_MAX / (n - i) + 1);
int t = array[j];
array[j] = array[i];
array[i] = t;
}
}
int main(){
const int begin = 10;
const int end = 30;
const int N = 12;
srand(time(0));
// array that contains elements 10, 11...30
int nums[end-begin];
for(int i=0;i<end-begin; i++){
nums[i] = begin+i;
}
// randomly shuffle array
shuffle(nums, end-begin);
// take first N elements
int result[N];
for(int i=0;i<N;i++){
result[i] = nums[i];
printf("%d ", result[i]);
}
}
Thanks for the help but after some more looking I found what I was doing wrong and now works.
code :
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
const int N=12;
int arr[N],i,j;
srand(time(0));
for(i=0;i<N;i++)
{
arr[i]=10+rand()%30;
}
for(i=0;i<N;i++)
{
for(j=i+1;j<N;j++)
{
if(arr[i]==arr[j])
{
do
{
arr[i]=10+rand()%30;
}
while(arr[i]==arr[j]);
}
}
printf(">>%d\t",arr[i]);
}
return 0;
}

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

Why does same program act different in ideone and codeblocks?

This code is designed to find the sum of digits of 100!. I get the correct ouput in ideone but the wrong one in codeblocks. Please help.
#include <stdio.h>
#include <stdlib.h>
#define size_of_number 160
#define question 100
//Function Prototypes
void initialise(int[]);
int sum_of_digits(int[]);
void factorial(int[],int);
int main()
{
int number[size_of_number];
int sum;
initialise(number);
factorial(number, question);
//Getting the sum of the digits of the number
sum = sum_of_digits(number);
printf("The sum of the digits of %d! is %d.\n",question, sum);
return 0;
}
//Initially, the number is 0 so all it's digits are set to zero.
void initialise(int number[])
{
int i;
for(i = 0; i < size_of_number; i++)
{
number[i] = 0;
}
}
//Finding the factorial by multiplying the digits
void factorial(int number[], int num)
{
int i, first_digit;
int carry, replace, product;
first_digit = 0;
number[first_digit] = 1;
while(num != 1)
{
carry = 0;
for(i = 0; i <= first_digit; i++)
{
product = num*number[i] + carry;
replace = product%10;
carry = product/10;
number[i] = replace;
if( (i == first_digit) && (carry > 0) )
{
first_digit++;
}
}
num--;
}
}
//Finding the sum of all digits
int sum_of_digits(int number[])
{
int i, sum;
for(i = 0; i < size_of_number; i++)
{
sum = sum + number[i];
}
return sum;
}
I had problems with some other programs too. Why s Codeblocks not giving the correct output which is 648 ?
You don't initialize sum in the function sum_of_digits. Normal local variables don't automatically get a starting value in C, so your program has what the C standard calls undefined behaviour. Anything can happen, but what typically does happen is that the variable starts with whatever data happened to be in the place in memory where the variable happened to be located.

How to generate random numbers in C two colons?

I need in c code that generates two numbers in horizontally...so that i can get token numbers for my login system.
I need that i get this:
token=0.152644,0.429187
so in example i have token= and random generated numbers that have at beginning 0. and then 6 random generated numbers separated with , sign.
How to get get this in C?
I have try this code but it does not give me what i want_
#include <stdio.h>
#include <string.h>
typedef
union
{
char tmp[sizeof(unsigned long long)];
unsigned long long myll;
} ll_t;
unsigned long long llrand(void)
{
FILE *in=fopen("/dev/urandom", "r");
ll_t ll_u;
fread(ll_u.tmp, sizeof(ll_u.tmp), 1, in);
fclose(in);
return ll_u.myll;
}
int main()
{
char tmp1[64]={0x0};
char working[64]={0x0};
int i=0;
for(i=0; i< 1; i++)
{
while(strlen(tmp1) < 6)
{
sprintf(working, "%lu", llrand() );
strcat(tmp1, working);
}
tmp1[6]=0x0;
printf("%s\n", tmp1);
*tmp1=0x0;
}
return 0;
}
From output i get this:
747563
102595
Can code be simple and short?
You can use rand() function:
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int randomNumber(int min, int max)
{
/* generate secret number between min and max: */
int res = rand() % (max-min+1) + min;
return res;
}
int main()
{
int i = 0;
srand (time(NULL));
for (i=0; i<100; i++)
printf("%d ", randomNumber(10, 1000000));
return 0;
}
That is full detail for rand():
http://www.cplusplus.com/reference/cstdlib/rand/
Here is the code that is working perfect:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n1, n2;
time_t t;
srand((unsigned) time(&t));
n1 = rand() % 1000000 + 1;
n2 = rand() % 1000000 + 1;
printf("token=0.%d,0.%d\n", n1, n2);
return 0;
}
And output is:
token=0.289384,0.930887
A propose a different approach. Instead of generating 2 numbers and format them into the output string, generate 12 different digits and put them directly in place.
srand(time(0));
char output[] = "taken=0.XXXXXX,0.YYYYYY";
for (int n = 0; n < 2; n++) {
for (int k = 0; k < 6; k++) {
output[9 * n + 8 + k] = rand() % 10 + '0';
// you might want to write a function that deals with rand() bias
}
}
puts(output);

Random number generator generating the wrong set of numbers

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
?

Resources