Initializing Arrays with a function - c

I'm trying to get an array to be initialized in a function. The initialized array should contain a set of random numbers within a certain range when working as intended. Is this possible in C?

#include <time.h> //time func for seed init
#include <stdlib.h> //srand/rand funcs
#include <stdio.h> //Library for printf function
#define LIMIT 100
void myFunction(int array[], int arrayIndexMaxSize){
for (int index = 0; index < arrayIndexMaxSize; index++){
array[index] = rand() % LIMIT; //Where limit is randomly produced from 0 - Limit inclusive
printf("array[%d] of arrayIndexMaxSize(%d) = %d\n", index, arrayIndexMaxSize, array[index]); //prints out th$
}
}
void main(){
srand(time(0)); //initializes kinda random number generator
int array[50]; //If known at runtime or compile time, must be at block scope meaing inside {curly} braces of any$
myFunction(array, 50);
}

Related

Changing the value of a variable with pointers not working

Basically I have a function called MinSubTab that is supposed to calculate the sum of the array passed and also to change the value passed in the first argument from inside the function without using return. This is done with pointers. Anyway, I think it'd be easier if I just showed you the code so here it is:
maintab.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "tab.h"
int main(){
int *reftab;
int min;
reftab = (int *)malloc(sizeof(int) * NMAX);
InitTab(reftab,NMAX);
printf("\n Total: %d et min: %d", MinSumTab(&min, reftab, NMAX), min);
free(reftab);
return 0;
}
tab.c
void InitTab(int *tab, int size){
srand(time(NULL));
for (int i=0; i<size; i++){
*(tab+i) = rand() % 10;
}
}
int MinSumTab(int *min, int *tab, int size){
int total=0;
int minimum = NMAX;
int temp = *min;
for (int i=0; i<size; i++){
total += *(tab+i);
}
for (int i=0; i<size; i++){
if(*(tab+i)<minimum){
minimum = *(tab+i);
}
}
*min = minimum;
return total;
}
So the expected result here is that the sum is printed (which it is) and the minimum value of the array is printed (which it is not). Every single time the min variable equals 8 and I've no idea how to actually change the value of min from within that function.
Please help as my brain has no more capacity for rational thought, it's been 1.5 hrs and no solution in sight. Thanks
Looks like a small mistake:
You initialize minimum with NMAX, which I assume is 8 (the size of the array). 99.9% of the random numbers will be bigger. So 8 is chosen as the minimum.
What you really want is to initialize it with RAND_MAX – the maximum value rand() can return.
In C order of evaluation and argument passing is undefined.
You can of course the order yourself but it only to feed your curiosity.
#include <stdio.h>
volatile char *message[] = {
"fisrt", "second", "third", "fourth"
};
int print(size_t x)
{
printf("%s\n", message[x]);
return x;
}
int main()
{
printf("%d %d %d %d\n", print(0), print(1), print(2), print(3));
return 0;
}
Note. There is one exception from this rule.
Logical operators are evaluated form the left to the right.
if( x != NULL && *x == 5)is safe because x will not be dereferenced if it is NULL

C - How would I extract Even numbers from an array and place them into another array called EvenNumbers?

I'm tasked with writing a function that will identify all the even numbers in an sample array {10,2,9,3,1,98,8] and place them in an array called EvenNumbers. I have to allow the function so that it works with different combinations of numbers in the array not just the numbers in the sample array above.
I'm wondering is there any way to add numbers to an array that could be different every time? How would I extract the even numbers an place them into an array? Also
for the even array size its giving me an error that the expression must have a constant value but when I use const int it still gives me that error.
Here is the full question.
"Using the array of sample values {10,2,9,3,1,98,8}, write a function that will identify all the even numbers in an array and place it in an array called EvenNumbers. The function must work in all cases, not just in the case of the array shown. Assume that the array size is always available through a global constant called MAX"
Here is what I have so far. I've no idea how I will extract the even numbers from a for loop and place them in an array. I also dont know what the "expression must have a constant value" is about?
#include <stdio.h>
#include <stdlib.h>
void EvenNumber(int Array[], int size);
int main()
{
int array[7] = { 10,2,9,3,1,98,8 };
EvenNumber(array, 7);
}
void EvenNumber(int Array[], int size)
{
int i;
int EvenArraySize;
for (i = 0; i < size; i++)
{
if (Array[i] % 2 == 0)
{
EvenArraySize++;
}
}
int Even[EvenArraySize];
}
The right way to go is to use malloc to allocate just the right amount of memory.
Count the number of even numbers
Allocate the space needed to store them
Copy even numbers in this space
Do whatever you want with these numbers
Free the allocated space
Snippet:
#include <stdio.h>
#include <stdlib.h>
#define MAX 7
int
main()
{
int array[] = {10,2,9,3,1,98,8};
int *even_numbers;
int i, nb_even_numbers;
for (i = 0, nb_even_numbers = 0; i < MAX; i++)
{
if (array[i] % 2 == 0)
nb_even_numbers++;
}
even_numbers = malloc(sizeof(int) * nb_even_numbers);
if (!even_numbers)
{
perror("malloc");
return 1;
}
for (i = 0, nb_even_numbers = 0; i < MAX; i++)
{
if (array[i] % 2 == 0)
even_numbers[nb_even_numbers++] = array[i];
}
/* do your stuff here */
free(even_numbers);
return 0;
}
First, you can never return a statically declared array from a function (even though you don't explicitly try, your Even array is destroyed when EvenNumber returns) Why? The function stack frame for EvenNumber is released for reuse on return and any locally declared arrays are no longer valid.
You either need to pass a second array as a parameter to EvenNumber, or you can dynamically allocate storage for Even in EvenNumber (with, e.g. malloc or calloc or realloc) and return a pointer to the beginning of the array. (you must also have some way to return the size or use a constant for a max size).
There is no need to use % (modulo) to test whether a number is odd/even. All you need to do is look at bit-0 (little endian). If it is 0, then the number is odd, if it is 1, then its even. Much more efficient than calling modulo which incorporates division.
Finally, main is type int and therefore returns a value.
Putting those pieces together, you can do something simple like the following:
#include <stdio.h>
#include <stdlib.h>
void EvenNumber (int *array, int *even, int size, int *esize);
int main (void)
{
int array[] = { 10,2,9,3,1,98,8 },
i, n = sizeof array / sizeof *array,
even[n], /* a VLA of the same size as array is fine here */
esize = 0;
EvenNumber (array, even, n, &esize);
printf ("array: ");
for (i = 0; i < n; i++)
printf (" %2d", array[i]);
printf ("\neven : ");
for (i = 0; i < esize; i++)
printf (" %2d", even[i]);
putchar ('\n');
return 0;
}
void EvenNumber (int *array, int *even, int size, int *esize)
{
int i;
for (i = 0; i < size; i++)
if ((array[i] & 1) == 0) /* simply looking at bit-0 is all you need */
even[(*esize)++] = array[i];
}
Note: esize is passed as a pointer to EvenNumber and updated within the function so that the number of elements in even are available back in the calling function (main() here).
Example Use/Output
$ ./bin/arrayeven
array: 10 2 9 3 1 98 8
even : 10 2 98 8
Let me know if you have any further questions.

Generate random letters in C

here is my code. I am trying generate random alphabet but i see same letters.
example: (YHTGDHFBSHXCHFYFUXZWDYKLXI) How can i fix it? just i need mixed alphabet not same letters. Thank you so much.
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void random_string(char * string, unsigned length)
{
/* Seed number for rand() */
srand((unsigned int) time(0));
int i;
for (i = 0; i < length; ++i)
{
string[i] = rand() % 26 + 'A';
}
string[i] = '\0';
}
int main(void)
{
char s[26];
random_string(s, 26);
printf("%s\n", s);
return 0;
}
The operation you are looking for is called a shuffle or a permutation. It is not sufficient to call a random-letter function 26 times, since, as you see, you can generate duplicates.
Instead, start with the string "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and perform a shuffle operation. If you want to learn by doing such things from scratch, I recommend reading about the Fisher-Yates Shuffle then crafting an implementation on your own.
You can do this by having a pool of available characters, and taking one from the pool. Please note that your target string was too short to accomodate the string terminator. Similar to Fisher Yates shuffle.
Edit: changed the types to size_t.
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LENGTH 26 // the cipher key length
void random_string(char * string, size_t length)
{
char pool[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
size_t poolsize = strlen(pool);
size_t index;
size_t i;
srand((unsigned)time(NULL));
for(i = 0; i < length && poolsize > 0; ++i)
{
index = rand() % poolsize; // a random index into the pool
string[i] = pool[index]; // take that character
pool[index] = pool[--poolsize]; // replace it with the last pool ...
} // ... element and shorten the pool
string[i] = '\0';
}
int main(void)
{
char s[LENGTH + 1]; // adequate length
random_string(s, LENGTH);
printf("%s\n", s);
return 0;
}
Program output:
QYMUSFALIZCXGONBJRETHPVKDW
// why program get errors this line? (unused variable cipher_text)
char *cipher_text, msg[255];
You declare cipher_text but you only use msg.
You could declare only:
char msg[255];
Copy paste from cplusplus.com/reference
The pseudo-random number generator is initialized using the argument
passed as seed.
For every different seed value used in a call to srand, the
pseudo-random number generator can be expected to generate a different
succession of results in the subsequent calls to rand.
Two different initializations with the same seed will generate the
same succession of results in subsequent calls to rand.
If seed is set to 1, the generator is reinitialized to its initial
value and produces the same values as before any call to rand or
srand.
In order to generate random-like numbers, srand is usually initialized
to some distinctive runtime value, like the value returned by function
time (declared in header ). This is distinctive enough for most
trivial randomization needs.
/* srand example */
#include <stdio.h> /* printf, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
printf ("First number: %d\n", rand()%100);
srand (time(NULL));
printf ("Random number: %d\n", rand()%100);
srand (1);
printf ("Again the first number: %d\n", rand()%100);
return 0;
}

How to create a matrix with random numbers using typedef struct?

I'm trying to write a function that creates a matrix with ones and zeroes which are randomly distributed, but I'm getting an error: expected identifier before numeric constant.
Can someone can give me some pointers on what I'm doing wrong?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 7
#define COLUMNS 7
typedef struct {
const int rows;
const int columns;
int board[ROWS][COLUMNS];
} game;
void newGame(game *session);
int main(void){
game session = {ROWS, COLUMNS};
srand(time(NULL));
return 0;
}
/* Function: newGame
* Description: Set up a new game with random states for each brick.
* Input: A pointer to the game structure.
* Output: The game structure pointed to is updated.
*/
void newGame(game *session){
for(int r = 0; r<ROWS; r++){
for(int c = 0; c<COLUMNS; c++){
session[r].ROWS = rand()%2;
session[c].COLUMNS = rand()%2;
}
}
}
This:
session[r].ROWS = rand()%2;
doesn't make any sense, session is a pointer to a single game, not an array, and ROWS is a #define that will be replaced by an integer here.
You probably meant:
session->board[r][c] = rand() % 2;
Also you are handling the size rather confusingly, it's both constant and run-time readable. I'm not sure that makes total sense to me, but perhaps it's handy for some reason.

Random number in for loop C

I need to generate 1000 random numbers inside a for loop.
my problem is that the random number generated is always the same. since im using time NULL to initiate the generator, why am i getting the same numbers? here is the code i used:
#include <stdio.h>
#include <stdlib.h>
#define LIMIT 30000
int main(){
int i;
srand((long) time(NULL));
for(i = 0; i < 1000; i++){
int x = rand() % LIMIT;
printf("%d\n", x);
}
}
If you run the program multiple times during the same second, you will pass the same value to the generator as seed. You have to wait at least a second before trying it again.
This is because the time function returns the number of seconds since a specific time, and if called multiple times during the same second will return the same value.
your code is right, but you forgot to include the time.h library.
#include <stdio.h>
#include <stdlib.h>
#include <time.h> // <--- now it works
#define LIMIT 30000
int main(){
int i;
srand((long) time(NULL));
for(i=0;i<1000;i++){
int x = rand() % LIMIT;
printf("%d",x);}

Resources