Write a program that will create an integer array with 1000 entries. After creating the array, initialize all of the values in the array to 0. Next, using the rand function, loop through the array and save a random number between 1 and 10 (inclusive) in each entry of the array.
This is for my homework due tomorrow but I need some help with it since I'm barely a beginner at code.
This is the only code I've made so far with single dimensional arrays
#include <stdio.h>
#include <stdlib.h>
int mean(int array[], int size);
int main()
{
int i;
int array[5]={5, 1, 3, 2, 4};
for (i=0; i<5; i++)
{
printf("%d", array[i]);
}
printf("\nThe mean is %d", mean(array,5));
return 0;
}
int mean(int array[], int size)
{
int i, sum = 0;
for (i=0; i<5; i++)
{
sum=sum + array[i];
}
return sum/5;
}
Not sure why you wrote a program to calculate the mean, given that there's nothing in the requirements about that.
However, you just have to think about the steps. Note that the following example do not perfectly match what you need, they're there just to show you the method, not to be cut and pasted into your assignment.
First, you can create an array of size (for example) seven with the statement:
int value[7];
You can then set all elements to a given value with:
for (size_t idx = 0; idx < sizeof(value) / sizeof(*value); idx++)
value[idx] = 42;
(although, at the level of your assignment, it's probably better to use 7 rather than the sizeof expression).
In order to generate random numbers, you first include the requisite header and, as the first thing in main(), set the seed to something "random":
#include <stdlib.h>
#include <time.h>
:
srand (time (0));
Then, at the time when you need to generate a random number from one to fifty inclusive, you can use:
int rnum = rand() % 50 + 1;
(keeping in mind the distribution won't be perfect but it should be more than good enough for the intended purpose here).
Whatever loop you chose above to initialise the array elements to 42 (or zero) can also be used to set them to random values.
That should be enough to get you started.
Related
This is an unfinished program I'm writing to learn C (only checks multiples of 2 currently...)
Ultimately, I want this to be an implementation of the Sieve of Eratosthenes (prime numbers)
The problem I'm having is that the output is non-deterministic: sometimes the output includes 11, other times it does not - This happens for a handful of numbers. I have experimented by changing a few things, such as actually initializing the array of booleans to false.
Any ideas why this might be happening?
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main(int argc, char *argv[]) {
int n = atoi(argv[1]);
int initialPrimeIterator = 2;
_Bool compositePrimeNumbers[n];
printf("Prime Numbers from 2 -> %d\n", n);
for (int i = initialPrimeIterator; i < n; i += initialPrimeIterator) {
compositePrimeNumbers[i-1] = true;
}
printf("Done...\n");
printf("Printing prime numbers from 2-> %d\n", n);
for (int i = 2; i < n; i++) {
if (!compositePrimeNumbers[i]){
printf("%d\n", i + 1);
}
}
return 0;
}
edit: haha. Just realized I have an array named 'compositePrime...' Should just be 'compositeNumbers'
Since I understand you are aiming at completing the program when overcoming this hurdle, I will not post a completed program, but only point out issues in your current version:
As it has been noted, the array compositePrimeNumbers is uninitialized. Since it must be initialized with all values false which is represented by 0, the quickest way is this:
memset(compositePrimeNumbers, 0, sizeof(compositePrimeNumbers));
You should not mark the current initialPrimeIterator as a composite number, hence the for-loop should start with the next multiple. Also, n must be included:
for (int i = 2 * initialPrimeIterator; i <= n; i += initialPrimeIterator) {
(actually, this can be optimized by replacing 2 * initialPrimeIterator with initialPrimeIterator * initialPrimeIterator).
With these changes, I believe you are well on the way to complete the program.
In C, a local array is not initialized, probably for performance reasons.
One way to fix this is to loop over it to set each element to false.
I am required to use Selection Sort to sort out arrays of the lengths of 100K, 150K, 200K and 1M and display the time required to sort out each array, and the number of element to element comparisons.
I did this by making an array having the elements as the lengths of the arrays. Then I ran a for loop with said array and passed the element being used as the size of the unsorted array to be created and created a randomly generated array.
I then use a function call to sort.
The program ran with no problem for my first 3 array lengths ( 100K, 150K and 200K ), however it did not run at all for 1M array length sorting.
I was not able to figure out at which point of the program was it stopping execution. I first thought that the problem lies with my integer declarations as some of them were storing quantities as big as a million. For this I put printf statements periodically to understand where the flow of the program was getting interrupted and it was surprisingly the array declaration ( this is what it seems like to me, not sure though ).
I have attached the code and output that I got.
Code:
// C program for implementation of selection sort
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
long long int counterS = 0; //counter for number of element to element comparisons
void swap(int *xp, int *yp) //swap function
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], long long int n)
{
long long int i, j, min_idx; //used long long int cuz they reach upto 10^6 order
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++) {
if (arr[j] < arr[min_idx])
min_idx = j;
++counterS; //increments each time a comparison occurs
}
// Swap the found minimum element with the first element
swap(&arr[min_idx], &arr[i]);
}
}
// Driver program to test above functions
int main()
{
clock_t tic1, toc1;
int sz[4]={100000,150000, 200000, 1000000}; //array having array lengths
int k;
for(k=0;k<4;k++){
printf("1st check: It's the long long int declaration\n"); //1st check to get to know where it went wrong
long long int size = sz[k];
printf("2nd check: It's the array declaration\n"); //2nd check to know where it went wrong
int arr[size];
printf("3rd check: It's not the array declaration\n"); //3rd check to know where it went wrong
long long int i;
for(i=0;i<size;i++)
arr[i]=rand()%100;
long long int n = sizeof(arr)/sizeof(arr[0]);
printf("4th check: It's the random array generation\n"); //4th check to know where it went wrong
tic1 = clock();
selectionSort(arr, n);
toc1 = clock();
double time_taken = (double)(toc1-tic1)/CLOCKS_PER_SEC;
printf("5th check: It's the function call\n"); //5th check to know where it went wrong
printf("Selection Sort - time = %lf seconds, element by element comparisons = %lld\n",
time_taken, counterS );
}
return 0;
}
Output:
1st check: It's the long long int declaration
2nd check: It's the array declaration
3rd check: It's not the array declaration
4th check: It's the random array generation
5th check: It's the function call
Selection Sort - time = 11.458000 seconds, element by element comparisons = 4999950000
1st check: It's the long long int declaration
2nd check: It's the array declaration
3rd check: It's not the array declaration
4th check: It's the random array generation
5th check: It's the function call
Selection Sort - time = 59.196000 seconds, element by element comparisons = 16249875000
1st check: It's the long long int declaration
2nd check: It's the array declaration
3rd check: It's not the array declaration
4th check: It's the random array generation
5th check: It's the function call
Selection Sort - time = 120.349000 seconds, element by element comparisons = 36249775000
1st check: It's the long long int declaration
2nd check: It's the array declaration
Define your large array outside any function.
int large[1000000];
int main(void) {
int sz[4] = {100000, 150000, 200000, 1000000};
for (int k = 0; k < 4; k++) {
// use the first sz[k] elements of large
}
}
Since everything else is working i would say you dont have enough bits to allocate a continious array of 1M size on the go, so as others commented i would suggest malloc() .
Others in your class may have this working because on their machine there is enough stack space to allocate 1M on the go. See if malloc() solves it and then you will know for sure.
I am currently trying to make a small game in the c programing language for a portfolio. I am new to c so I don't know all of the ticks. Currently, I am trying to assign values to enum's though I don't know if that is correct.
// C program for generating a
// random number in a given range.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "Test.h"
enum mods{
Cha, Str, Dex, Con, Int, Wis // <-this line is the only line that is my code (of this document I have more that will reference this document) the rest I learned from others
};
// Generates and prints 'count' random
// numbers in range [lower, upper].
void printRandoms(int lower, int upper,
int count)
{
int i;
for (i = 0; i < count; i++) {
int num = (rand() %
(upper - lower + 1)) + lower;
printf("%d ", num);
}
}
// Driver code
int main(enum mods Str)
{
int lower = 6, upper = 18, count = 1;
// Use current time as
// seed for random generator
srand(time(0));
printRandoms(lower, upper, count);
printf("My enum Value : %d\n", (int)Str);
return 0;
*edit Sorry for the confusion. I want to be able to reference this product of this line of code over and over again in the main sheet/program. I want it to be a random start so it isn't the same game every time. How do I do that? (for an example of the end product:
if (Str >= 10)
printf("pass skill check to lift the log\n");
else
printf("you drop the log on your foot and take 1d4 damage\n");
enum (health -1d4[will make actual code for this but not yet])
what I need answered
how to make each of the enum mods = a random number at the start of the program to be referenced in the main program
)
If I understood you correctly, you want the mod values to be randomly generated.
Use the enum values as array indices into an array big enough to hold all your mod attributes. Like this, for example:
enum mods = { Cha, Str, Dex, Con, Int, Wis, Mod_Max };
int mod_values[Mod_Max];
Keeping Mod_Max (or whatever you'd like to call it) as the last element of the enum, this will give you simple way to refer to the size of the array. Populating the array with values:
for (int i = 0; i < Mod_Max; i++) {
mod_values[i] = ...;
}
And getting a value of a given "mod" would simply be (for example Str):
mod_values[Str];
EDIT: This way, lets you further modify the mod values down the line, rather than having them as constants
I believe you're asking how to have values for each element in your enum. Well all you have to do is simply assign said value-
enum mods { foo = 77, bar = 42, baz = 3 };
Then you can access said values like so-
enum mods mod_enum = foo;
printf("%d", mod_enum);
The above will print 77
You can also directly use the value of one of the elements from said enum
printf("%d\n", bar);
The above prints 42
Read more about enums
I wrote two functions and call the functions in main.
Function 1 – I wrote a function that returns void and takes an int * (pointer to integer array) or int[], and int (for the size). The function needs to initialize all the elements of the array to non-zero values.
Function 2 – I wrote another function that returns int and takes an const int * (pointer to integer array) or int[], and int (for the size). The function should sum all the elements of the array and return the sum.
In main I defined an integer array of size 5. Called function 1 in main to initialize the values of the array. Called function 2 in main to get the sum and print the value of the sum to the console.
My problem is the program runs but the print out for sum we are getting is a large (in the millions), random, number and is not the expected answer of 15. Anyone who can help us get the correct answer would be greatly appreciated
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#pragma warning(disable: 4996)
void func1(int* ptr, int size);
int func2(const int* ptr, int size);
int main()
{
int grid[5];
func1(grid, 5);
func2(grid, 5);
}
void func1(int* ptr, int size)
{
*ptr = 1, 2, 3, 4, 5;
}
int func2(const int* ptr, int size)
{
int sum;
sum = ptr[0] + ptr[1] + ptr[2] + ptr[3] + ptr[4]; // *(ptr + 0); putting an asterisk makes it so that it changes the entire "ptr" value and the "[0]" value
printf("\n\nThe sum of the integers in the array is %d.\n\n", &sum);
}
*ptr = 1, 2, 3, 4, 5;
does not do what you think it does. It actually evaluates all the integer constants but sets ptr[0] to be 1 (see comma operator for more detail), leaving all the others at some arbitrary value.
Note that it is not evaluating *ptr = (1, 2, 3, 4, 5) (which would set *ptr to 5) but is actually evaluating (*ptr = 1), 2, 3, 4, 5 - this works because something like 42 is actually a valid C statement, albeit not very useful.
If you're trying to set the array to increasing values, just use something like:
for (int i = 0; i < size; i++)
ptr[i] = i + 1;
You probably also want to do that when summing the values since it should depend on the passed-in size rather than just summing five values:
int sum = 0;
for (int i = 0; i < size; i++)
sum += ptr[i];
Additionally, the value you are printing out is not the sum, it's the address of the variable containing the sum (a decent compiler will warn you about this). You should be using sum in your printf rather than &sum.
And, as a final note, the signature for func2 indicates that you should actually be returning the sum rather than just printing it. So I would suggest removing the printf from that function and simply doing:
return sum;
Then you can put the printf into the caller (main) as follows:
int main(void)
{
int grid[5];
func1(grid, sizeof(grid) / sizeof(*grid));
int sum = func2(grid, sizeof(grid) / sizeof(*grid));
printf("The sum of the integers in the array is %d.\n\n", sum);
return 0;
}
Note the use of sizeof(grid) / sizeof(*grid), which is basically the number of array elements in grid - this will allow you to resize grid by simply changing it in one place to something like int grid[42] and still have all the code work with the updated size.
Not actually necessary for your code but it's best to get into good programming habits early (more descriptive names for your functions may also be a good idea).
Line *ptr = 1, 2, 3, 4, 5; assigns ptr[0] value and leaves other spots unitilized so when you sum it, it will be random memory.
You should use for like this to initialize
for(int i=0;i<size;i++)
{
ptr[i] = i+1;
}
and similiar aproach to sum it.
I am writing a program which have to generate N random not repeating numbers
the prototype should be voidrandom_int(int array[], int N);
it is not having any errors but it is not working. Not even giving any number
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void random_init(int array[], int N)
{
srand(time(NULL));
int i, j;
array[0]=rand()%N;
for(i=1;i<N;i++)
{
array[i]=rand()%N;
if(array[i]==0)
array[i]=1;
for(j=0;j<i;j++)
{
if(array[i]==array[j])
break;
}
if((i-j)==1)
continue;
else
i--;
}
}
int main(void)
{
int a[5], i, N;
N=5;
random_init(a,N);
for(i=0;i<N;i++)
printf("%d ", a[i]);
return 0;
}
This part makes no sense:
if(array[i]==0)
array[i]=1;
It will limit your choices to N-1 numbers (1 to N-1), out of which you try to find N numbers without repetition - leading to an infinite loop.
if((i-j)==1)
continue;
Here you probably want if (i==j) instead, to check if the previous loop ran to completion.
A faster and simpler way to generate the numbers 0..N-1 in a random order, is to put these numbers in an array (in sequential order), and then use Fisher-Yates Shuffle to shuffle the array.
This method is biased. Do not use it other than for educational purposes.
Other than Ficher-Yates, which uses another array, you can use the method of going through all the available numbers and find a "random" spot for them (effectively "initializing" the array twice). If the spot is taken, choose the next one. Something like this, in pseudo-code:
fill array with N
for all numbers from 0 to N-1
find a random spot
while spot is taken (value is N) consider next spot /* mind wrapping */
set value in current spot