











C++ program for removing duplicate element in an array
Program to remove duplicates from an array
Here is a program to remove duplicate elements in an array. Given an array, all the duplicate elements of the array are removed.
For example, consider the array
Example
Input: arr = {1, 2, 3, 4, 4}
Output: arr = {1, 2, 3, 4}


Algorithm:-
- Input the number of elements of the array.
- Input the array elements.
- Repeat from i = 1 to n
- if (arr[i] != arr[i+1])
- temp[j++] = arr[i]
- temp[j++] = arr[n-1]
- Repeat from i = 1 to j
- arr[i] = temp[i]
- return j.
C++ Code:-
//c++ program for removing duplicate element in an array
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int remove_duplicate_elements(int arr[], int n)
{
if (n==0 || n==1)
return n;
int temp[n];
int k = 0;
int i;
for (i=0; i<n–1; i++)
if (arr[i] != arr[i+1])
temp[k++] = arr[i];
temp[k++] = arr[n–1];
for (i=0; i<j; i++)
arr[i] = temp[i];
return k;
}
void main(String[] args)
{
int n;
cout<<“\nEnter no. of elements you want in an array :”;
cin>>n;
int *a = new int[n+1];
cout<<“\nEnter all the elements”);
for(int i = 0; i < n; i++)
{
cin>>a[i];
}
n = remove_duplicate_elements(a, n);
cout<<“\nArray after removing element :”;
for(int i=0;i<=n; i++)
cout<<a[i]<<” “;
}
}
OUTPUT
Enter size of an array
6
Enter elements in an array
1
2
3
3
4
5
After removing duplicate elements
1,2,3,4,5
Login/Signup to comment