Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*this code delete all duplicate elements and make the array the distinct element array*/
- #include<stdio.h>
- #include<malloc.h>
- int n;
- void shrink_arr(int *arr, int j)
- {
- if(j==n-1)
- arr[j]=0;//considering all elemet to be non-zero
- else
- { while(j<n-1)//keep shrinking till the last element
- /*'j' can maximum travel up to the 2nd last element so that j+1 become the last one*/
- {arr[j]=arr[j+1];
- j++;
- }
- }
- /*Since each time the shrink fun called the array shrink by 1 element so n--;*/
- n--;
- return;
- }
- int main()
- {
- int *arr,i,j;
- printf("Enter number of elements:. ");
- scanf("%d",&n);
- arr= calloc(n,sizeof(int));
- //Enter all (distinct) elements of array/
- for(i=0;i<n;i++)
- { printf("Enter element %d: ",i+1);
- scanf("%d",&arr[i]);
- }
- printf("\n Here is the list:\n");
- for(i=0;i<n;i++)
- printf("%d ",arr[i]);
- for(i=0;i<n;i++)
- { for(j=i+1;j<n;j++)//for each element to compare with all other element we need to for loop (nested)
- { while(arr[i]==arr[j])//if more than two consecutive numbers are equal
- { shrink_arr(arr,j);
- }
- }
- }
- /*Print the list after deleting all duplicate elements*/
- printf("\n List with distinct element:\n");
- for(i=0;i<n;i++)
- printf("%d ",arr[i]);
- free(arr);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement