Programming Examples

Cpp program to remove duplicate elements from an array using for loop


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

Solution

#include<iostream>
using namespace std;
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];
    }
     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;
            }
        }
    }
    cout << "Array without duplicates: ";
    for (int i = 0; i < size; ++i) {
        cout << arr[i] << " ";
    }
    cout << endl;
    return 0;
}
Output

Desired array size

6

Enter the elements in an array

12

13

12

1

4

1

Array without duplicates: 12 13 1 4

Latest Current Affairs 2024 Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2024 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