Programming Examples

Cpp program to remove duplicate elements from an array using function


Write a program to remove the duplicate elements from an array using function 

Solution

#include<iostream>
using namespace std;

// Function declaration
int removeDuplicates(int arr[], int size);

int main() {
    int arr[50],size;
    cout<<"Desired array size";
    cin>>size;
    cout<<"Enter the elements in an array";
    for(int a=0;a<size;a++)
    {
        cin>>arr[a];
    }

    // Remove duplicates using the function
    size = removeDuplicates(arr, size);

    cout << "Array without duplicates: ";
    for (int i = 0; i < size; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;

    return 0;
}
// Function definition
int removeDuplicates(int arr[],int size){
    for (int i = 0; i < size; i++) {
        //cout<<"Value of i is"<<i<<endl;
        for (int j = i + 1; j < size; j++) {
            // cout<<"Value of j is"<<j<<endl;
            if(arr[i]==arr[j]) {
                //cout<<"REPEATED Number is : "<<arr[i]<<" ";
                // Shift elements to the left starting from the duplicate element
                for (int k = j; k < size - 1; k++) {
                    arr[k] = arr[k + 1];
                   // cout<< "new Value "<<arr[k]<<endl;
                }
                size--;
                //cout<<"Size is :"<<size<<endl;
            }
        }
    }
    return size;
}
Output

Desired array size

7

Enter the elements in an array

12

13

4

5

4

13

6

Array without duplicates: 12 13 4 5 6 

CCC Online Test 2021 CCC Practice Test Hindi Python Programming Tutorials Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Bank SSC Railway TET UPTET Question Bank career counselling in allahabad Sarkari Naukari Notification Best Website and Software Company in Allahabad Sarkari Exam Quiz