Program in C and C++ to remove duplicate elements from array.
C
CPP
#include<stdio.h> #define size 25 int removeDup(int a[],int *n) { int i,j,flag=0; for(i=0;i<*n;i++) { for(j=i+1;j<*n;j++) { if(a[i]==a[j]) { flag=1; for(j=i;j<*n;j++) a[j]=a[j+1]; *n=*n-1; //return 1; } } } if(flag==0) return 0; else return 1; } int main() { int n,a[size],i; printf("Enter the size of array."); scanf("%d",&n); if(n>size) { printf("Invalid array size."); return 0; } printf("Enter %d numbers.:-",n); for(i=0;i<n;i++) scanf("%d",&a[i]); printf("\nElements of array before remove.\n"); for(i=0;i<n;i++) printf("%4d",a[i]); if(removeDup(a,&n)==1){ printf("\nElements of array after remove.\n"); for(i=0;i<n;i++) printf("%4d",a[i]); } else printf("\nNot any data is duplicate."); return 0; }
#include<iostream> using namespace std; int removeDup(int a[],int *n) { int i,j,flag=0; for(i=0;i<*n;i++) { for(j=i+1;j<*n;j++) { if(a[i]==a[j]) { flag=1; for(j=i;j<*n;j++) a[j]=a[j+1]; *n=*n-1; //return 1; } } } if(flag==0) return 0; else return 1; } int main() { const int size=25; int n,a[size],i; cout<<"Enter the size of array."; cin>>n; if(n>size) { cout<<"Invalid array size."; return 0; } cout<<"Enter "<<n<<" numbers.:-"; for(i=0;i<n;i++) cin>>a[i]; cout<<"\nElements of array before remove.\n"; for(i=0;i<n;i++) cout<<" "<<a[i]; if(removeDup(a,&n)){ cout<<"\nElements of array after remove.\n"; for(i=0;i<n;i++) cout<<" "<<a[i]; } else cout<<endl<<"Not any data is duplicate."; return 0; }
Output:-
0 Comments