I should mention that I am in my 1st 2 weeks of an intro to programming class before people get too crazy with answers.
Using this array as an example,
int scores[30] = {90,85,100,50,50,85,60,70,55,55,80,95,70,60,95,
80,100,75,70,95,90,90,70,95,50,65,85,95,100,65}
I am trying to parse through it to create 2 new parallel arrays to use later. The idea is to make one array that holds the "scores" and one that holds the "occurrences" of each score. I end up compiling with no errors however during run time it crashes.
void frequency(int scores[], int max){
int i, x=0, temp=0, count=0, sum=0, mode=0;
int score[sum]; //unknown length of array, sum gets added after the while loop
int freq[sum];
printf("score\tfrequency\n");
printf("-----\t---------\n");
fprintf(fp, "score\tfrequency\n");
fprintf(fp, "-----\t---------\n");
for (i = 0; i < max; ++i){
while (scores[i]==scores[x]){
x++;
count++;
sum++;
temp = x-1;
if(scores[i] != scores[x]){
//printf(" %d\t %d\n",scores[i], count);
freq[i] = count;
score[i] = scores[i];
count=0;
i=temp;
x=temp+1;
sum++;
printf("%d\t%d", score[i], freq[i]);
fprintf(fp, "%d\t%d", score[i], freq[i]);
}
}
}
}
This part:
int i, x=0, temp=0, count=0, sum=0, mode=0;
int score[sum];
int freq[sum];
looks wrong.
You set sumto zero and then use it for the array dimension. Did you mean to do:
sum = max;
I end up compiling with no errors however during run time it crashes.
Reason:
The reason why your program crashes is because you have not allocated sufficient memory to the arrays that you use int the frequency() function
void frequency(int scores[], int max){
int i, x=0, temp=0, count=0, sum=0, mode=0;
int score[sum];
int freq[sum];
Solution:
So, is there a way to provide memory during run time according to requirements or change memory size of blocks during compile time?
Yes, that's the very reason why Dynamic memory allocation is used.... though you send a fixed array to the frequency() function in your code, the function I've provided works for any integer array you send..
Here I've provided code in which
one array stores all the unique scores
and other array stores number of occurrences of each score
I've done this using dynamic memory allocation.. I think it's easy to understand if you have basic understanding of dynamic memory allocation functions.. if you have any doubts, ask me through the comments :) and by the way I've assumed your main function to be :
int main()
{
int scores[30] = {90,85,100,50,50,85,60,70,55,55,80,95,70,60,95,
80,100,75,70,95,90,90,70,95,50,65,85,95,100,65};
frequency(scores,30);
return 0;
}
Code:
#include <stdio.h>
#include <stdlib.h>
void frequency(int scores[], int max);
int main()
{
int scores[30] = {90,85,100,50,50,85,60,70,55,55,80,95,70,60,95,
80,100,75,70,95,90,90,70,95,50,65,85,95,100,65};
frequency(scores,30);
return 0;
}
void frequency(int scores[], int max)
{
int i,j,count=0,flag=0,occur=0;
int *score=malloc(sizeof(int));
if(malloc==NULL)
{
printf("memory allocation failed");
exit(1);
//it's good to check if memory allocated was successful or not
//I've avoided it for further allocations,to decrease the size of post :)
}
int *freq=malloc(sizeof(int));
printf("score\tfrequency\n");
printf("-----\t---------\n");
//building array which has only scores
for(i=0;i<max;i++)
{
if(count==0) //first time
{
score=realloc(score,(count+1)*sizeof(int));
//increasing size of array by 1*sizeof(int)
score[count]=scores[i];
count++;
}//first one requires no checking whether it's repeated or not
else
{
flag=0; //resetting flag value
for(j=0;j<count;j++)
{
if(scores[i]==score[j])
{
flag=1; //
break;
}
}
if(flag==0) // if not repeated need to add new element
{
score=realloc(score,(count+1)*sizeof(int));
score[count]=scores[i];
count++;
}
}
}
//allocating memory for frequency array
freq=realloc(freq,count*sizeof(int));
//building array which has frequency of each score
for(i=0;i<count;i++)
{
occur=0;
for(j=0;j<max;j++)
{
if(score[i]==scores[j])
occur++;
}
freq[i]=occur;
}
for(i=0;i<count;i++) //printing output
printf("\n %d\t %d\n",score[i],freq[i]);
free(score); //freeing the blocks
free(freq);
}
My approach is quite simple to understand
first I create array score which creates extra memory whenever it encounters unique elements and stores in it
and then I check occurrences for each of the element of score array in the scores array and store them in freq array.
Output:
score frequency
----- ---------
90 3
85 3
100 3
50 3
60 2
70 4
55 2
80 2
95 5
75 1
65 2
I hope this is what you were trying to achieve :)
Related
Im in the process of learning C and the basis of the class is C primer plus(6th edition). We use Eclipse as an IDE.
For an project we have to create to arrays. One array that takes numbers in a loop and another array that display the cumulative value. So if array 1 has values 1, 5 and 3(out of 10 inputs total) then the resulting input in array 2 should be 9(on the 3th input because of the 3 inputs in array 1).
Im having trouble getting started the right way - anyone here has ideas how I could proceed?
So far I have this for starters but forgive me for it it very weak:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
void doublearrays (double usernumber);
int main(void)
{
double usernumbers = 0.0;
int loop1 = 1;
while(loop1)
{
printf("Type numbers as doubles. \n");
fflush(stdout);
loop1 = scanf("%lf", &usernumber);
if(loop1)
{
doublearrays(usernumber);
}
}
return 0;
}
All the text in a homework assignment shall be read:
For a project we have to create two arrays... 10 inputs total...
Why on earth do not you declare them?... You already have defined SIZE so
double usernumbers[SIZE];
double cumulnumbers[SIZE];
Next do yourself a favour and handle one problem at a time:
One array that takes numbers in a loop...
Ok, so write a loop up to 10 reading floats directly into the array and note how many numbers were received
int n;
for(n=0; n<SIZE; n++) {
if (scanf("%lf", &usernumbers[n]) != 1) break;
}
// ok we now have n number in the first array
Let us go on
and another array that display the cumulative value.
Ok cumul is initially 0. and is incremented on each value from the first array:
double cumul = 0.;
for(int i=0; i<n; i++) {
cumul += usernumbers[i];
cumulnumbers[i] = cumul;
}
(your current code isn't what you need... delete it and then...)
anyone here has ideas how I could proceed?
Well the first step would be to actually define some arrays.
double input[SIZE];
double cum[SIZE];
The next step would be a loop to read input.
for (int i = 0; i < SIZE; ++i)
{
if (scanf("%lf", &input[i]) != 1)
{
// Input error - add error handling - or just exit
exit(1);
}
}
The next step is to add code for calculating the the cumulative value.
I'll leave that for you as an exercise.
The last step is to print the array which I also will leave to you as an exercise.
The straight forward way of doing this, which would also use two arrays and a loop construct would be to create something like this.. I've changed the doubles to integers. (and i am also ignoring any errors from scanf()).
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
static void
print_array(int *arr, const char *arr_name)
{
int i;
printf("%s = [");
for (i = 0; i < SIZE; i++)
printf("%d%s", arr[i], i < SIZE -1 ? ",":"");
printf("]\n");
}
int main(int argc, char **argv)
{
int i;
int input[SIZE];
int cumsum[SIZE];
for (i = 0; i < SIZE; i++)
{
int _input;
printf("Give me numbers!\n");
fflush(stdout);
scanf("%d", &_input); /* assuming integer */
input[i] = _input;
cumsum[i] = i > 0 ? cumsum[i-1] + _input : _input;
}
print_array(input, "input");
print_array(cumsum, "cumulative");
return 0;
}
or If you'd like to play around with pointers and have a bit more compact version.. perhaps this could be something to study to help you understand pointers, it does the same thing as my code above
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
static int data[SIZE*2];
int main(int argc, char *argv[])
{
int *input_p = &data[0];
int *cumsum_p = &data[0] + SIZE;
for (; input_p != &data[0] + SIZE; input_p++, cumsum_p++)
{
printf("Give me numbers!\n");
scanf("%d", input_p);
*cumsum_p = input_p == &data[0] ? *input_p : *(cumsum_p-1) + *input_p;
}
}
I am attempting to create a dynamic array that will grow in size if needed, as I don't know how large the array will actually be. My code seems to work until the 8th element of the array where I start to see very large incorrect values that I did not enter. Not sure why this is happening.
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char** argv)
{
int val;
int userInput;
int* arr;
int size = 1;
int arrIndex = 0;
arr = (int*) malloc(sizeof(int) * size);
/* prompt the user for input */
printf ("Enter in a list of numbers to be stored in a dynamic array.\n");
printf ("End the list with the terminal value of -999\n");
/* loop until the user enters -999 */
scanf ("%d", &val);
while (val != -999)
{
if (arrIndex >= size)
{
size++;
}
arr[arrIndex] = val;
arrIndex++;
/* get next value */
scanf("%d", &val);
}
int j = 0;
for(j = 0; j < size ; j++)
{
printf("%d \t", arr[j]);
}
}
The size of the array remains 1 and doesn't increase while incrementing size variable.
Your code worked until 8th element because adjacent memory after the array upto 7th element must be free.
In C array index out of bound is not checked and it is programmers responibility.
if you want to increase or decrease size of array you can use realloc inside while loop:
arr=(int*)realloc(arr,sizeof(int)*size);
Also Correct this if condition in your code initially arrayindex is 0 and size is 1 which results in false.
if (arrIndex >= size)
{
size++;
}
I'm trying to write a program that calculates the cumulative sum of a dynamically allocated vector filled with random values using only pointers(without any other type of variable).I think I managed to do that but now I want an improvement:
-I want a maximum of two variables used and without malloc(the size of the vector should be fixed
and not be read by the user,for example the number of items collected should be 10). Some suggestions?
my code:
#include <stdio.h>
#include <malloc.h>
#include <time.h>
int main() {
int *n=malloc(sizeof(int)); // memory allocation for required variables
int *sum=malloc(sizeof(int));
int *a;
srow(time(NULL));
printf("Define the size of array A \n");
scanf("%d", n);
if (*n < 1) { // the size must be > 0
puts("Invalid size");
return 1;
}
printf("Generates random values... \n");
a=malloc(sizeof(int) * *n); //allocates array of int's
*sum=0; //reset the sum
while ((*n)--) {
a[*n]= row() % 1000 + 1; // add random numbers in the array from 1 to 1000
*sum += a[*n]; //add values
}
printf("The sum of all the elements in the array=%d\n", *sum);
return 0;
}
Recursion is an academic curiosity. In real world computing, you want to avoid it like the plague. I mention this because there's an answer here that would depend on recursion to ensure that we're only creating 'two variables'. We're not really, since all variables are just stack objects, and we're abusing the stack to avoid creating variables. Anyway, with newer versions of C you can define stack arrays using the array notation like such:
int array[count];
And you can avoid pointers completely this way. Out two 'variables' are thus array and count, as shown below.
int main() {
// Initialize all variables to known values
int count = 0;
// Seed the random number generator
srand(time(NULL));
printf("Define the size of array A \n");
scanf("%d", &count);
// the size must be > 0
if (count < 1) {
printf("Invalid size\n");
} else {
int array[count];
printf("Generating %d random values...\n", count);
fill_array( array, count );
// Sum the array of values
sum_array( array, count );
printf("The sum of all the elements in the array=%d\n", sum);
}
}
To have the function fill_array not use any variables, we'll use a do-while loop.
void fill_array(int *array, int size) {
do array[--size] = rand() % 1000;
while (size != -1);
}
Finally, we'll use recursion to get our sum, also without any new variables.
int sum_array(int* array, int size) {
if(!size) return 0;
else return sum_array(array, size - 1) + array[size - 1];
}
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main()
{
int i=0,pos;
int *ptr;
clrscr();
ptr=(int *)malloc(10*sizeof(int));
printf("Enter 10 Elements:\n");
while(i<10)
{
scanf("%d",&ptr[i]);
i++;
}
printf("Current Array:\n");
for(i=0;i<10;i++)
{
printf("%d\t",ptr[i]);
}
printf("Enter the position to be deleted:");
scanf("%d",&pos);
for(i=pos;i<10;i++)
{
ptr[pos-1]=ptr[pos];
pos++;
}
for(i=0;i<10;i++)
{
printf("%d\t",ptr[i]);
}
getch();
}
Array i enter : 1 2 3 4 5 6 7 8 9 0
Suppose 4th position has been deleted
Array after deletion: 1 2 3 5 6 7 8 9 0 0
How can i make the program to print only 9 integers but without decresing the times the loop run.
i.e. without using
for(i=0;i<9;i++)
C doesn't allow you to do that. So, alternative is to dynamically allocate an array, put what you want in it, then when you get the size you want, transfer that data to a newly allocated array of the appropriate size and delete the old one.
Use a variable to keep track of how many elements of the array are being used.
When you start:
unsigned num_elements = 10;
int *ptr = malloc(num_elements * sizeof(int));
When you delete, do the following as well:
--num_elements;
When you print:
for (unsigned i=0; i<num_elements; ++i) {
...
}
Since you print the array in multiple places in the code, it would be nice to create a small function to do it.
void print_array(int *a, unsigned size) {
if (size == 0) {
printf("[empty]\n");
return;
}
printf("%d", a[0]);
for (unsigned i=1; i<size; ++i) {
printf("\t%d", a[i]);
}
printf("\n");
}
print_array(ptr, num_elements);
Your questions refers to 2 issues here:
Deleting an element of an dynamically allocated array
Printing values of an dynamically allocated array without adjusting for loop parameters
1)
for(i=pos;i<10;i++)
{
ptr[pos-1]=ptr[pos];
pos++;
}
Does not decrease the array at all - you just overwrite the particalur position with another element but you still have memory allocated for 10 int
One way to reach that would be using realloc after you moved the values by to the left beginning at the target element:
for (i = pos; i < array_size - 1; i++)
{
ptr[i] = ptr[i+1];
}
ptr = realloc(ptr, --array_size)
To 2)
Simple answer: This wont be possible. When you decrease the size of your array and dont adjust the loop's paramter you will access memory which doesnt belong to the array anymore.
Of course you dont want to adjust every for-loop by hand but you can simplify life if you always remember the array's size, preferably in immediate reference to it within a struct:
typedef struct
{
size_t size;
int *array;
} my_array_t;
If you ensure that size is properly adjusted everytime you allocate the array's memory (functions are your friend), you can always print the values with:
my_array_t a;
a.size = 10;
a.array = malloc(a.size * sizeof(int));
for (i=0; i < a.size; i++)
// ...
It seems a very trivial problem but after a lot of thinking I still can't figure it out. I worte these two codes for Radix sort.
Code 1
#include <stdio.h>
#include <malloc.h>
#define BUCKET_SIZE 10
void prin(int* arr,int n)
{
int i;
for(i=0;i<n;i++)
printf("%d ",*(arr+i));
printf("\n");
}
int maxi(int* arr,int n)
{
int i,max=0;
for(i=0;i<n;i++)
{
if(arr[i]>max)
max=arr[i];
}
return max;
}
int* count(int *arr,int n,int k)
{
int* count,i,index;
int* output;
count=(int*)calloc(BUCKET_SIZE-1,sizeof(int));
output=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
index=(arr[i]/k)%10;
count[index]++;
}
for(i=0;i<BUCKET_SIZE;i++)
count[i]+=count[i-1];
for(i=n-1;i>=0;i--)
{
index=(arr[i]/k)%10;
output[count[index]-1]=arr[i];
count[index]--;
}
return output;
}
int* radixsort(int* arr,int n)
{
int i,max,k=1;
max=maxi(arr,n);
while(max>0)
{
max/=10;
arr=count(arr,n,k);
k=k*10;
}
return arr;
}
void main()
{
int n,i;
scanf("%d",&n);
int* arr;
arr=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
scanf("%d",(arr+i));
arr=radixsort(arr,n);
prin(arr,n);
}
Now if I change the sort subroutine like below, this code will not sort the given array and I can't figure why this happened, I am still traversing the whole array so and I am still calculating the right index so my elements should be filled in the right place and I should have a sorted array.
Code 2
Only count function last loop changed.
int* count(int *arr,int n,int k)
{
int* count,i,index;
int* output;
count=(int*)calloc(BUCKET_SIZE-1,sizeof(int));
output=(int*)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
index=(arr[i]/k)%10;
count[index]++;
}
for(i=0;i<BUCKET_SIZE;i++)
count[i]+=count[i-1];
for(i=0;i<n;i++)
{
index=(arr[i]/k)%10;
output[count[index]-1]=arr[i];
count[index]--;
}
return output;
}
When I am doing just counting sort both functions work well. Can someone point me out where I am going wrong with radix sort, or what is the thing I am missing, and how both well in counting sort.
Thanks.
In your final loop in your count function,
when these lines copy the contents of each "bucket",
they write the last element of the output "bucket" first,
followed by the next-to-last, ending with the first element:
output[count[index]-1]=arr[i];
count[index]--;
In the first version of your program, since you visit the elements of the input array starting at the end of the array and working your way back toward the beginning,
you encounter the last element of each bucket first (and therefore put it in the last position in the output bucket), then the next-to-last element
(which you put in the next-to-last position in the output),
and so forth. The first element of each bucket is the last copied
and is copied to the first position in the bucket.
In the second version of your program, you continue to fill in the spaces in each output bucket from back to front, but you read the input from front to back. This has the result of putting the first element of each bucket in the last position within that bucket, and the last element of the bucket in the first position.
That is, each time you run the count function it reverses the order of elements within each bucket.
If you want to copy the input array reading it from front to back,
you need to fill in each output bucket from front to back
by using ++count[index] instead of --count[index].
You also have to start each entry of count[index] at a lower number so that you write to the correct locations.
Aside: your program does a lot more allocation than it needs to, and doesn't free any memory, so you have a potentially massive memory leak.
You might consider passing already-allocated arrays into count instead of always allocating new ones.
Here is a front to back example, that also replaces the original array with a sorted array, freeing the original array. An alternative would be to do a one time allocation of a second working array, radix sort back and forth between original and working arrays, then keep the sorted array, and free the "other" array.
#include <stdio.h>
#include <stdlib.h>
#define BUCKET_SIZE 10
void prin(int* arr, int n)
{
int i;
for(i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int maxi(int* arr, int n)
{
int i,max = 0;
for(i = 0; i < n; i++)
{
if(arr[i] > max)
max = arr[i];
}
return max;
}
/* replaces array with sorted array, frees original array */
void count(int** parr, int n, int k)
{
int* count, i, index;
int* arr = *parr;
int* output;
int sum, cur;
count=calloc(BUCKET_SIZE, sizeof(int));
output=malloc(n*sizeof(int));
for(i = 0; i < n; i++){
index = (arr[i]/k)%10;
count[index]++;
}
sum = 0;
for(i = 0; i < BUCKET_SIZE; i++){
cur = count[i];
count[i] = sum;
sum += cur;
}
for(i = 0; i < n; i++){
index = (arr[i]/k)%10;
output[count[index]++] = arr[i];
}
free(arr);
free(count);
*parr = output;
}
void radixsort(int** parr,int n)
{
int max,k=1;
max=maxi(*parr,n);
while(max>0)
{
max/=10;
count(parr,n,k);
k=k*10;
}
}
int main()
{
int n,i;
int* arr;
scanf("%d",&n);
arr = malloc(n*sizeof(int));
for(i = 0; i < n; i++)
scanf("%d",&arr[i]);
radixsort(&arr,n);
prin(arr,n);
free(arr);
return 0;
}