add and remove elements from an array - c

i m working on this small C program to fill an array, insert and remove elements from an array and finally printing that array.
The program consists of a main() function, the addToArray() function,
remFromArray() function and the printArray() function.
here's my main method:
which prompts the user for a sequence of positive integers
• for each integer entered by the user, call the addToArray function to insert the integer into the array
• call the printArray function to print out the content of the array.
NOTE:do not prompt the user for the number of integers to be entered; you must accept input until the user enters a negative number
#include <stdio.h>
#define maxSize 100 //maxSize for array
int addToArray(int* arr, int size, int numToAdd);
int remFromArray(int* arr, int size, int numToGo);
void printArray(int* arr, int size);
int main (void){
int arr[maxSize];
int i, j;
printf("Enter a positive integer to add to an array\n");
while (i >= 0 ){
scanf("%d",&i);
if (i >= 0 ) {
addToArray(arr, maxSize, i);
printf("Enter another positive integer for array\n");
}
else{
printArray(arr, maxSize);
}
}
}
these are my other function that i created:
addToArray() =>
/*find the correct index in the array where to insert the
new element, so array in ascending order
- make room for the new element by moving other elements
- store the new element at the correct index
- return the new size (number of elements) of the array */
int addToArray(int* arr, int size, int numToAdd){
int i, n, m, pos;
for (int i = 0; i < maxSize; i++)
{
if (numToAdd < arr[i])
{
pos = i;
break;
}
if (numToAdd > arr[n-1])
{
pos = maxSize;
break;
}
}
if (pos != maxSize)
{
m = maxSize - pos + 1 ;
for (int i = 0; i <= m; i++)
{
arr[maxSize - i + 2] = arr[maxSize - i + 1] ;
}
}
arr[pos] = numToAdd;
}
void printArray(int* arr, int size){
printf("Resultant array is\n");
for (int c = 0; c <= maxSize; c++){
printf("%d\n", arr[c]);
}
}
as you can see I've tried writing the main(), addToArray(), printArray(), but for some reason its not working right. my printArray() is not displaying the desired result.
I'll be glad if you could look at this code and guide me through it.
thanks a million

First, you don't set values to the variables you create. For exemple, all of those int i, n, m, pos; have indeterminate values, not 0 as you might expect. Don't forget to asign them a value before using to avoid bad surprises.
Second, be carefull about indexes of your array. For example, arr[maxSize - i + 2], when i == 0, then the index will be maxSize + 2, witch is invalid position and can lead to segmentation fault.

Related

Array Rotation with Getting Max Value and Index Location of Array C language

I'm creating a program that gets the index value of the highest element in an array.
Sample Input:
4 (Size of a[])
1 2 4 3 (Elements of a[])
2 (Size of rotate[])
0 2 (Elemnts of rotate[])
Output will be:
2
0
Using left rotation.
In the First Rotation (0) the location will be 2 because 4 is the highest a[1,2,4,3]
In the Second Rotation (2) the location will be 0 because 4 is the highest a[4,3,1,2]
Problem is i'm not getting the desired output and there was a warning in for(j=0;j<rotateValue;j++)
I want the function to be as it is and to fix this part to int* output = getMaxIndex(a,rotate);
but i don't know how.
Thank you in advance for helping!
#include<stdio.h>
int i,j,k; // for looping
int n, m; // sizes of arrays
int getMaxIndex(int* a[], int* rotate[])
{
int indices[m];
for(i=0;i<m;i++)
{
int* rotateValue = rotate[i];
for(j=0;j<rotateValue;j++) // for rotation
{
int* first = a[0];
for(i=0;i<n-1;i++)
{
a[i] = a[i+1];
}
a[n-1] = first;
}
int location;
int* max = a[0];
for(j=0;j<n;j++) // getting the max element
{
if(a[j] > max)
{
max = a[j];
// printf("Max added");
}
}
for(j=0;j<n;j++) // getting the location
{
if(max == a[j])
{
location = j;
// printf("Loc added");
}
}
indices[i] = location;
}
// for(i=0;i<m;i++) // printing here to know if correct
// {
// printf("%d",indices[i]);
// }
return *indices;
}
int main()
{
scanf("%d",&n); // inputting array size
int* a[n];
for(i=0;i<n;i++) // filling elements of a[]
{
scanf("%d",&a[i]);
}
scanf("%d",&m); // inputting rotate array size
int* rotate[m];
for(i=0;i<m;i++) // filling elements of rotate[]
{
scanf("%d",&rotate[i]);
}
int* output = getMaxIndex(a,rotate); // call function
for(i=0;i<m;i++) // printing output
{
printf("%d",output[i]);
}
}
int getMaxIndex(int* a[], int* rotate[]);
Designing getMaxIndex() in the following way should solve most of the issues:
int* getMaxIndex(int a[], int rotate[])
{
static int indices[MAX_POSSIBLE_VALUE_OF_M];
/*
your code
*/
return indices;
}
Now, all you have to do is adjust your code in the main() function accordingly.
Why declare the array indices[] in getMaxIndex() as static int?
indices[] is a local variable of getMaxIndex(). And so after the return statement of getMaxIndex() is executed, it shall be destroyed. That means, if you return indices[] to main(), the main function will not be able to access indices[] anymore. And this issue can be solved by declaring indices[] as a static int instead of int.
NOTE: static array should have constant size. So, its size should be declared as maximum possible value of m instead of m.
Required adjustments in main():
Declare a[] and rotate[] as int instead of int*.
Check out my code.I am getting the correct output. I have written down a few mistakes that you have made.
void getMaxIndex(); //function declaration
int n, m; //for storing array size
int * a, * rotate;
int main(void) {
int i; //to use in loops
scanf("%d", & n); // inputting array size
a = (int * ) malloc(n * sizeof(int));
for (i = 0; i < n; i++) // filling elements of a[]
{
scanf("%d", & a[i]);
}
scanf("%d", & m); // inputting rotate array size
rotate = (int * ) malloc(m * sizeof(int));
for (i = 0; i < m; i++) // filling elements of rotate[]
{
scanf("%d", & rotate[i]);
}
getMaxIndex();
free(a);
free(rotate);
return 0;
}
void getMaxIndex() {
int i;
int aMax, rotateMax;
int aMaxIndex, rotateMaxIndex;
aMax = a[0];
rotateMax = rotate[0];
for (i = 1; i < n; i++) {
if (aMax < a[i]) {
aMax = a[i];
aMaxIndex = i;
}
}
for (i = 1; i < m; i++) {
if (rotateMax < rotate[i]) {
rotateMax = rotate[i];
rotateMaxIndex = i;
}
}
printf("%d\n%d", aMaxIndex, rotateMaxIndex);
}
My suggestions:
Always try to allocate memory for your array dynamically so that you can avoid errors such as Segmentation Fault or Core Dump.
In your code you have used array of pointers instead of pointers, there you went wrong. Try refering to your textbook or other sources to get a clear idea regarding pointers.
For example, in your code you passed your array named indices using the line:
return indices;
Now, to pass a pointer you don't need to use asterisk(). Simply write: return indices;
Also, don't use asterisk symbol to declare an array.
Your Code:
int* a[n];
Here you are declaring an array of pointers not an array.
Correct code:
int a[n];
But I liked your logic. You just have to implement it with the correct syntax. Just keep practicing.
I the code which I've written is understood by you, my work here is done. Happy Coding!!!

Complexity to find if there is a missing element in an array

I am trying to write a function (in C) that checks if an array has all the elements (between 0 and its "size-1")
For example, if the array's size is 3, it should have {0, 1, 2 } in any order.
The question is: what is the most efficient complexity to do this without an extra array?
The complexity of my attempt, showed below, is (average of nlogn + n).
edit: sorry for the miss understanding, any whole number can be an input, which means checking size wont work --> {0, 0, 3}
int check_missing_element(int *a, int n)
{
int i = 0;
quicksort(a, 0, n - 1);
for (i = 0; i < n; i++)
{
if (a[i] != i)
return 0;
}
return 1;
}
Walk the array using the value [0...n-1] of the element as the next element to visit.
As leaving each element, set its value to n. Any visited element with an n has already been visited and so is a failure - unless we have indexed ourselves. Any element with a value outside [0...n-1] is a failure.
After 'n' visits we are done. O(n).
Sort not needed. This does consume the array.
Here is an implementation of the cycle-chasing algorithm sketched in chux’ answer, along with a test program.
/* Return 1 iff each integer in 0...n-1 appears exactly once in a[0]...a[n-1].
Return 0 otherwise.
*/
int check_missing_element(int *a, int n)
{
// Reject elements that are out of bounds.
for (int i = 0; i < n; ++i)
if (a[i] < 0 || n <= a[i])
return 0;
// Define a value to mark already seen values with.
static const int AlreadySeen = -1;
// Work through the array.
for (int i = 0; i < n; ++i)
// If we already examined this element, ignore it.
if (a[i] != AlreadySeen)
{
/* Follow the cycle defined by x -> a[x]. If we encounter an
already seen element before returning to i, report rejection.
Otherwise, mark each encountered element seen.
*/
for (int j = a[i]; j != i;)
{
int next = a[j];
if (next == AlreadySeen)
return 0;
a[j] = AlreadySeen;
j = next;
}
}
// Every element has been seen once and only once. Report acceptance.
return 1;
}
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Define a comparator for sorting int values in ascending order.
static int Comparator(const void *a, const void *b)
{
int A = * (const int *) a;
int B = * (const int *) b;
return
A < B ? -1 :
A == B ? 0 :
+1;
}
// Provide a reference routine for testing check_missing_elements.
static int check_missing_elementReference(int *a, int n)
{
/* Sort the elements. Iff the array contains each value exactly once,
this results in an array containing 0, 1, 2, 3,... n-1.
*/
qsort(a, n, sizeof *a, Comparator);
// Test the sorted array.
for (int i = 0; i < n; ++i)
if (a[i] != i)
return 0;
return 1;
}
#define ArrayLimit 7
#define NumberOf(a) (sizeof (a) / sizeof *(a))
/* Define a structure used to iterator through test values.
The indices in the Index array will each run from -x to n, inclusive,
where x is the number of special values (defined below) and n is the array
size. The indices will be incremented lexicographically (odometer style).
For the indices from -x to -1, the associated value will be one of the
special values. For the indices from 0 to n, the associated value will
equal the index. Note that n is outside the bounds of array values that
pass the test. It is included in testing so that rejections based on it
are tested.
*/
typedef struct
{
int Index [ArrayLimit];
int Values[ArrayLimit];
} Iterator;
// Define special values to include in testing.
static const int SpecialValues[] = { INT_MIN, -1, INT_MAX };
/* Define the number of special values as an int, not a size_t, because we use
its negation and so need a signed type.
*/
#define NumberOfSpecialValues ((int) NumberOf(SpecialValues))
// Initialize an iterator.
static void InitializeIterator(Iterator *Iterator, int n)
{
for (int i = 0; i < n; ++i)
{
Iterator->Index [i] = -NumberOfSpecialValues;
Iterator->Values[i] = SpecialValues[0];
}
}
/* Increment an iterator. Return 0 if we are done (all fields rolled over,
bringing the iterator back to the initial state) and 1 otherwise.
*/
static int Increment(Iterator *Iterator, int n)
{
// Start at the rightmost field.
int j =n-1;
while (0 <= j)
{
// If this field has room to increase, increment it.
if (Iterator->Index[j] < n)
{
++Iterator->Index[j];
/* Set the associated value to either a special value or the
index value, as described above.
*/
Iterator->Values[j] =
Iterator->Index[j] < 0
? SpecialValues[Iterator->Index[j] + NumberOfSpecialValues]
: Iterator->Index[j];
// There is no carry into the next field, so we are done.
return 1;
}
/* This field rolls over and resets to its initial value. Then we
carry into the next field.
*/
Iterator->Index [j] = -NumberOfSpecialValues;
Iterator->Values[j] = SpecialValues[0];
--j;
}
// All fields rolled over, so we are done.
return 0;
}
// Print an array.
static void PrintArray(int *a, int n)
{
printf("[");
if (0 < n)
printf("%d", a[0]);
for (int i = 1; i < n; ++i)
printf(", %d", a[i]);
printf("]");
}
int main(void)
{
// Test each array size up to the limit.
for (int n = 1; n <= ArrayLimit; ++n)
{
// Iterator through all array values.
Iterator i;
for (InitializeIterator(&i, n); Increment(&i, n);)
{
/* Since the routines destroy the array, copy the array. Then
execute the routine and record the return value.
*/
int Buffer[ArrayLimit];
// Reference routine first.
memcpy(Buffer, i.Values, n * sizeof *Buffer);
int expected = check_missing_elementReference(Buffer, n);
// Subject routine.
memcpy(Buffer, i.Values, n * sizeof *Buffer);
int observed = check_missing_element (Buffer, n);
// Test for a bug.
if (expected != observed)
{
printf("Failure:\n");
printf("\tArray = "); PrintArray(i.Values, n); printf("\n");
printf("\tExpected %d but observed %d.\n", expected, observed);
exit(EXIT_FAILURE);
}
}
printf("Array length %d: Passed.\n", n);
}
}

My pointer in an array doesn't work as it supposed to

I wanted to create a function, that would accept an 1:array_of_int, and 2:size_of_array, then return sum of the 3 biggest int. Code follows:
#include <stdio.h>
#include <stdlib.h>
int max_3(int arr[], int asize)
{
int max_arr[3];
int max =0;
int sum = 0;
int* pi;
for(int j=0; j<3; j++)
{
for(int i =0; i<asize;i++)
{
if(arr[i] > max)
{
max = arr[i];
pi = (arr + i); // to know the address of the max int of 'i' cycle
}
}
max_arr[j] = max;
*pi = 0; // make the max int = 0 so that the next 'i' cycle doesnt have the previous max in it
//(so it can look for another max value - the second one)
}
for(int i=0; i<3; i++)
sum += max_arr[i];
return sum;
}
int main (int argc, char** argv) {
int arr[6] = {1,5,9,12,16,14};
printf("%i\n",max_3(arr, 6));
return (EXIT_SUCCESS);
}
The pointer pi doesn't make the value of the current max value 0, and the next cycle in for (int i..) make the biggest one again as from the previous. So instead of returning max val1 + val2 + val3, it returned 3 * val1 (the biggest one) -- in my particular example - it printed out 48 instead of 42 (12 + 16 + 14) - as it should. But how when I make the value of address (which my pointer point to) as 0? I do not understand that properly.
Your if statement:
if (arr[i] > max)
isn't going to be entered after the first time you find max (i.e. when j > 0).
You need to zero it after:
max_arr[j] = max;
max = 0;
The following proposed code:
performs the desired functionality
is very straight forward in its' algorithm
incorporates a bubble sort for selecting the top three entries in the array
eliminates the 'magic' number 6
modifies the second parameter to type size_t as that is the type returned by sizeof()
the expression: sizeof(arr)/sizeof(arr[0]) lets compiler calculate number of entries in array
the statement: int arr[] = {1,5,9,12,16,14}; lets compiler allocate room for array
avoids modifying the original array, when sorting
and now, the proposed code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // memcpy()
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], size_t n)
{
size_t i;
size_t j;
for (i = 0; i < n-1; i++)
{
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(&arr[j], &arr[j+1]);
}
}
}
}
int max_3(int arr[], size_t asize)
{
int localArray[ asize ];
memcpy( localArray, arr, asize*sizeof( int ) );
// sort array
bubbleSort( localArray, asize );
// calculate sum of max 3 entries
int sum = localArray[asize-1] + localArray[asize-2] + localArray[asize-3];
return sum;
}
int main ( void )
{
int arr[] = {1,5,9,12,16,14};
printf( "%i\n", max_3( arr, sizeof(arr)/sizeof(arr[0])) );
return (EXIT_SUCCESS);
}
a run of the proposed code results in:
42
After the very first iteration of the outer loop (the loop for(int j=0; j<3; j++)) the value of max and pi will never change.
In that first iteration of the outer loop, you will find that the fifth element in the array will be largest, max will be equal to 16 and pi will point to that element. You set max_arr[0] to 16 and set *pi to zero. Then the outer loop starts over with max still being equal to 16. And now there will be no value in the array that will be equal or larger than that. So you set max_arr[1] to 16 as well, and set *pi (where pi is still pointing to the fifth element) to zero again. And the same thing the next iteration.
The natural solution would be to define max and pi inside the outer loop:
for(int j=0; j<3; j++)
{
// The variables will be redefined and reinitialized each iteration of the loop
int max = 0;
int *pi;
for(int i =0; i<asize;i++)
{
if(arr[i] > max)
{
max = arr[i];
pi = (arr + i); // to know the address of the max int of 'i' cycle
}
}
max_arr[j] = max;
*pi = 0; // make the max int = 0 so that the next 'i' cycle doesnt have the previous max in it
//(so it can look for another max value - the second one)
}
There are a few other problems with the code, like for example the possibility that pi will never be initialized. I leave it as an exercise to the reader to figure when that will happen and how to solve it.

C Mergesort Segfault

Situation
I was trying to implement a more interesting mergesort that creates a random length array with random values and then randomizes them, but after debugging and compiling it segfaults. I don't know why it segfaults, but I'm sure it's related to memory allocation.
Question
Why does this code cause a segfault?
Code
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Declare some stuff up front
int array_size(int *array);
int print_array(int *array);
//Some decade old main function coming at you
int main() {
//Concerned with the integrity of my rand
srand( (unsigned)time( NULL ));
//A global, random length array between 1 and 100?
int *array;
array = malloc(sizeof(*array) * ((rand() % 100) + 1));
init_array(*array);
getchar();
return 0;
}
int init_array(int *array) {
//Base case
array[0] = 1;
//random values for i in array
int i;
for(i = 1; i <= array_size(array); i++) {
array[i] = rand() % array_size(array) + 1;
}
//randomize the random values in the random length array
for (i = 0; i < (array_size(array) - 1); i++)
{
unsigned int swapA = (rand() % array_size(array)) + 1;
int a = array[swapA];
array[swapA] = array[i];
array[i] = a;
}
//output random array, then mergeSort the array
print_array(array);
sort_array(array);
return 0;
}
//Get my array.Length
int array_size(int *array) {
return sizeof(array)/sizeof(array[0]);
}
//Output array
int print_array(int *array) {
int i;
for(i = 0; i < (array_size(array) + 1); i++) {
printf("%d\n", array[i]);
}
return 0;
}
//merge the array after sorting
void merge_array(int *array, int low, int split, int high) {
int sorted[high-low+1];
int a = 0;
int b = low;
int c = split + 1;
//iterate from beginning to middle and from middle to end in parallel
while(b <= split && c <= high)
{
if(array[b] < array[c])
{
sorted[a++] = array[b++];
}
else
{
sorted[a++] = array[c++];
}
}
while(b <= split) sorted[a++] = array[b++];
while(c <= high) sorted[a++] = array[c++];
int i;
for(i = 0; i < a; i++) {
array[i+low] = sorted[i];
}
print_array(array); //Print sorted array
}
//Sort the array
int sort_array(int *array, int low, int high) {
int split = ( low + high ) / 2;
if( low < high ) {
sort_array(array, low, split);
sort_array(array, split + 1, high);
merge_array(array, low, split, high);
}
}
return sizeof(array)/sizeof(array[0]);
The above statement evaluates to 1 (assuming sizeof(int *) = sizeof(int), as pointed out by H2CO3).
Try something like this,
int main() {
//Concerned with the integrity of my rand
srand( (unsigned)time( NULL ));
//A global, random length array between 1 and 100?
int *array;
int number_of_elements = (rand() % 100) + 1;
array = malloc(sizeof(*array) * num_of_elements);
init_array(*array, num_of_elements);
getchar();
return 0;
}
Pass the number of elements as arguments to init_array instead of calculating it every time.
This seems to be the problem:
//Get my array.Length
int array_size(int *array) {
return sizeof(array)/sizeof(array[0]);
}
You essentially return sizeof(int*)/sizeof(int), which is not what you want. This whole thing appears because arrays decay into pointers when passed to functions.
You should read the Arrays and Pointers section in the comp.lang.c FAQ for edification.
What happens when you run your program with /WALL? What warnings are being spat out? Why?
What happens when you step through your program with a debugger attached? What is the value of each variable at each line? Why?
There are several problems with your code:
You don't check the result of malloc to see if it returned NULL.
You are passing the dereference of array to init_array, i.e. you are sending the first int of the array to init_array which then promptly dereferences it. Since malloc returns garbage data, you're dereferencing a random number inside of init_array.
array_size is not magic. If you do not track the size of your arrays in C, you cannot retrospectively find out how big you wanted them to be. You need to remember the size of the array and pass it to init_array.

Removing Duplicates from an Array using C [duplicate]

This question already has answers here:
Algorithm: efficient way to remove duplicate integers from an array
(34 answers)
Closed 8 years ago.
I want small clarification in array concept in C.
I have array:
int a[11]={1,2,3,4,5,11,11,11,11,16,16};
I want result like this:
{1,2,3,4,5,11,16}
Means I want remove duplicates.
How is it possible?
You can't readily resize arrays in C - at least, not arrays as you've declared that one. Clearly, if the data is in sorted order, it is straight-forward to copy the data to the front of the allocated array and treat it as if it was of the correct smaller size (and it is a linear O(n) algorithm). If the data is not sorted, it gets messier; the trivial algorithm is quadratic, so maybe a sort (O(N lg N)) followed by the linear algorithm is best for that.
You can use dynamically allocated memory to manage arrays. That may be beyond where you've reached in your studies, though.
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
static int intcmp(const void *pa, const void *pb)
{
int a = *(int *)pa;
int b = *(int *)pb;
if (a > b)
return +1;
else if (a < b)
return -1;
else
return 0;
}
static int compact(int *array, int size)
{
int i;
int last = 0;
assert(size >= 0);
if (size <= 0)
return size;
for (i = 1; i < size; i++)
{
if (array[i] != array[last])
array[++last] = array[i];
}
return(last + 1);
}
static void print(int *array, int size, const char *tag, const char *name)
{
int i;
printf("%s\n", tag);
for (i = 0; i < size; i++)
printf("%s[%d] = %d\n", name, i, array[i]);
}
int main(void)
{
int a[11] = {1,2,3,4,5,11,11,11,11,16,16};
int a_size = sizeof(a) / sizeof(a[0]);
print(a, a_size, "Before", "a");
a_size = compact(a, a_size);
print(a, a_size, "After", "a");
int b[11] = {11,1,11,3,16,2,5,11,4,11,16};
int b_size = sizeof(b) / sizeof(b[0]);
print(b, b_size, "Before", "b");
qsort(b, b_size, sizeof(b[0]), intcmp);
print(b, b_size, "Sorted", "b");
b_size = compact(b, b_size);
print(b, b_size, "After", "b");
return 0;
}
#define arraysize(x) (sizeof(x) / sizeof(x[0])) // put this before main
int main() {
bool duplicate = false;
int a[11] = {1,2,3,4,5,11,11,11,11,16,16}; // doesnt have to be sorted
int b[11];
int index = 0;
for(int i = 0; i < arraysize(a); i++) { // looping through the main array
for(int j = 0; j < index; j++) { // looping through the target array where we know we have data. if we haven't found anything yet, this wont loop
if(a[i] == b[j]) { // if the target array contains the object, no need to continue further.
duplicate = true;
break; // break from this loop
}
}
if(!duplicate) { // if our value wasn't found in 'b' we will add this non-dublicate at index
b[index] = a[i];
index++;
}
duplicate = false; // restart
}
// optional
int c[index]; // index will be the number of objects we have in b
for(int k = 0; k < index; k++) {
c[k] = b[k];
}
}
If you really have to you can create a new array where that is the correct size and copy this into it.
As you can see, C is a very basic (but powerful) language and if you can, use a vector to but your objects in instead (c++'s std::vector perhaps) which can easily increase with your needs.
But as long as you only use small numbers of integers you shouldn't loose to much. If you have big numbers of data, you can always allocate the array on the heap with "malloc()" and pick a smaller size (maybe half the size of the original source array) that you then can increase (using realloc()) as you add more objects to it. There is some downsides reallocating the memory all the time as well but it is a decision you have to make - fast but allocation more data then you need? or slower and having the exact number of elements you need allocated (which you really cant control since malloc() might allocate more data then you need in some cases).
//gcc -Wall q2.cc -o q2 && q2
//Write a program to remove duplicates from a sorted array.
/*
The basic idea of our algorithm is to compare 2 adjacent values and determine if they
are the same. If they are not the same and we weren't already looking previusly at adjacent pairs
that were the same, then we output the value at the current index. The algorithm does everything
in-place and doesn't allocate any new memory. It outputs the unique values into the input array.
*/
#include <stdio.h>
#include <assert.h>
int remove_dups(int *arr, int n)
{
int idx = 0, odx = -1;
bool dup = false;
while (idx < n)
{
if (arr[idx] != arr[idx+1])
{
if (dup)
dup = false;
else
{
arr[++odx] = arr[idx];
}
} else
dup = true;
idx++;
}
return (odx == -1) ? -1 : ++odx;
}
int main(int argc, char *argv[])
{
int a[] = {31,44,44,67,67,99,99,100,101};
int k = remove_dups(a,9);
assert(k == 3);
for (int i = 0;i<k;i++)
printf("%d ",a[i]);
printf("\n\n");
int b[] = {-5,-3,-2,-2,-2,-2,1,3,5,5,18,18};
k = remove_dups(b,12);
assert(k == 4);
for (int i = 0;i<k;i++)
printf("%d ",b[i]);
printf("\n\n");
int c[] = {1,2,3,4,5,6,7,8,9};
k = remove_dups(c,9);
assert(k == 9);
for (int i = 0;i<k;i++)
printf("%d ",c[i]);
return 0;
}
you should create a new array and you should check the array if contains the element you want to insert before insert new element to it.
The question is not clear. Though, if you are trying to remove duplicates, you can use nested 'for' loops and remove all those values which occur more than once.
C does not have a built in data type that supports what you want -- you would need to create your own.
int a[11]={1,2,3,4,5,11,11,11,11,16,16};
As this array is sorted array, you can achieve very easily by following code.
int LengthofArray = 11;
//First elemnt can not be a duplicate so exclude the same and start from i = 1 than 0.
for(int i = 1; i < LengthofArray; i++);
{
if(a[i] == a[i-1])
RemoveArrayElementatIndex(i);
}
//function is used to remove the elements in the same as index passed to remove.
RemoveArrayElementatIndex(int i)
{
int k = 0;
if(i <=0)
return;
k = i;
int j =1; // variable is used to next item(offset) in the array from k.
//Move the next items to the array
//if its last item then the length of the array is updated directly, eg. incase i = 10.
while((k+j) < LengthofArray)
{
if(a[k] == a[k+j])
{
//increment only j , as another duplicate in this array
j = j +1 ;
}
else
{
a[k] = a[k+j];
//increment only k , as offset remains same
k = k + 1;
}
}
//set the new length of the array .
LengthofArray = k;
}
You could utilise qsort from stdlib.h to ensure your array is sorted into ascending order to remove the need for a nested loop.
Note that qsort requires a pointer to a function (int_cmp in this instance), i've included it below.
This function, int_array_unique returns the duplicate free array 'in-place' i.e. it overwrites the original and returns the length of the duplicate free array via the pn pointer
/**
* Return unique version of int array (duplicates removed)
*/
int int_array_unique(int *array, size_t *pn)
{
size_t n = *pn;
/* return err code 1 if a zero length array is passed in */
if (n == 0) return 1;
int i;
/* count the no. of unique array values */
int c=0;
/* sort input array so any duplicate values will be positioned next to each
* other */
qsort(array, n, sizeof(int), int_cmp);
/* size of the unique array is unknown at this point, but the output array
* can be no larger than the input array. Note, the correct length of the
* data is returned via pn */
int *tmp_array = calloc(n, sizeof(int));
tmp_array[c] = array[0];
c++;
for (i=1; i<n; i++) {
/* true if consecutive values are not equal */
if ( array[i] != array[i-1]) {
tmp_array[c] = array[i];
c++;
}
}
memmove(array, tmp_array, n*sizeof(int));
free(tmp_array);
/* set return parameter to length of data (e.g. no. of valid integers not
* actual allocated array length) of the uniqe array */
*pn = c;
return 0;
}
/* qsort int comparison function */
int int_cmp(const void *a, const void *b)
{
const int *ia = (const int *)a; // casting pointer types
const int *ib = (const int *)b;
/* integer comparison: returns negative if b > a
and positive if a > b */
return *ia - *ib;
}
Store the array element with small condition into new array
**just run once 100% will work
!)store the first value into array
II)store the another element check with before stored value..
III)if it exists leave the element--and check next one and store
here the below code run this u will understand better
int main()
{
int a[10],b[10],i,n,j=0,pos=0;
printf("\n enter a n value ");
scanf("%d",&n);
printf("\n enter a array value");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);//gets the arry value
}
for(i=0;i<n;i++)
{
if(check(a[i],pos,b)==0)//checks array each value its exits or not
{
b[j]=a[i];
j++;
pos++;//count the size of new storing element
}
}
printf("\n after updating array");
for(j=0;j<pos;j++)
{
printf("\n %d",b[j]);
} return 0;
}
int check(int x,int pos,int b[])
{ int m=0,i;
for(i=0;i<pos;i++)//checking the already only stored element
{
if(b[i]==x)
{
m++; //already exists increment the m value
}
}
return m;
}

Resources