Hi Guys,
I am trying to enter a rand() in my code below, but it is causing a problem. It says 'a' not intialized.
Since 'a' is a pointer I didn't think I had to have it equal to anything. I am a beginner at this so maybe I am missing something along the code......
Code:// Program to process integers inputed by user in acending order and showing the number of times each number appears // The use of rand() to investigate the random output and calloc to assign allocate memory for these integer inputed by user. #include <stdio.h> #include <stdlib.h> int main (void) { int *a; int i = 0, j=0, n, freq = 0;// input and increment variables printf("Enter numbers from 1 to 10:");// input from user scanf_s("%d", &n); for(i = 0; i <= 7; i++) { *(a+i) = rand()%10 + 1;//creates random array(instead of scanf which allocates a memory to an array elements) } for (j =1;j <= 10; j++)// prints values inside of the array from 1 - 10 a = calloc(n, sizeof(int));// allocates memory for pointers, as random numbers can be entered by users { for ( i = 0; i <= 7; i++)//fills array - loops around until gone through all 8 elements { if (j == *(a+i)) //searches array for no. 1 to 10 and assigns value (j) to a[i] { ++freq;//count of no of time a particular no. comes up } } if(freq!=0) printf("%d occurs %d times\n", j, freq);// output freq = 0; } return 0; }
This is the actual assignment:
(Im not after the answer, just thought it might be useful plus im beyond frustrated...)
Write a program that reads n integers, in the range 1 to 10, into an array, then prints on a separate line the value of each distinct element along with the number of times it occurs. The values should be printed in descending order. Suppose, for example that you input the values
1 3 3 1 5 5 3
as the elements of your array. Then your program should print
5 occurs 2 times
3 occurs 3 times
1 occurs 2 times
Use your program to investigate the output of rand(). First use rand() to generate an array of 100 random integers in the range 1 to 10. To generate an integer in the range 1 to 10, use the following code
rand() % 10 +1
Rewrite your program to make use of calloc, allow the user to enter the number of random integers to be generated and use this to dynamically create the array.
Remember: to use calloc in C, either name your file filename.c or cast the result of calloc using the cast (int*).
Finally rewrite your program so that it uses pointers instead of array indices. Your final version should contain no ‘square’ brackets (‘[‘,’]’).
You only need to submit this final version of your code.