Advertisement
Mr_kindle

distinctarray.c

Nov 9th, 2022 (edited)
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.55 KB | None | 0 0
  1. /*this code delete all duplicate elements and make the array the distinct element array*/
  2.  
  3.  
  4. #include<stdio.h>
  5. #include<malloc.h>
  6.  
  7. int n;
  8.  
  9. void shrink_arr(int *arr, int j)
  10. {    
  11.         if(j==n-1)
  12.              arr[j]=0;//considering all elemet to be non-zero
  13.                  
  14.            
  15.      else
  16.         { while(j<n-1)//keep shrinking till the last element
  17.         /*'j' can maximum travel up to the 2nd last element so that j+1 become the last one*/
  18.             {arr[j]=arr[j+1];
  19.             j++;
  20.             }
  21.         }
  22.         /*Since each time the shrink fun called the array shrink by 1 element so n--;*/
  23.         n--;
  24.         return;
  25. }
  26.  
  27. int main()
  28. {
  29.    int *arr,i,j;
  30.      printf("Enter number of elements:. ");
  31.     scanf("%d",&n);
  32.     arr= calloc(n,sizeof(int));
  33.     //Enter all (distinct) elements of array/
  34.     for(i=0;i<n;i++)
  35.     {    printf("Enter element %d: ",i+1);
  36.         scanf("%d",&arr[i]);
  37.     }
  38.    
  39.     printf("\n Here is the list:\n");
  40.     for(i=0;i<n;i++)
  41.       printf("%d ",arr[i]);
  42.    
  43.     for(i=0;i<n;i++)
  44.     {    for(j=i+1;j<n;j++)//for each element to compare with all other element we need to for loop (nested)
  45.             {    while(arr[i]==arr[j])//if more than two consecutive numbers are equal
  46.                     {    shrink_arr(arr,j);
  47.                     }
  48.             }
  49.     }
  50.     /*Print the list after deleting all duplicate elements*/
  51.     printf("\n List with distinct element:\n");
  52.     for(i=0;i<n;i++)
  53.       printf("%d ",arr[i]);
  54.    
  55.    
  56.    
  57.    
  58.    
  59.     free(arr);
  60.    return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement