Programming Examples

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


Write a program to remove the duplicate elements from an array using while 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];
    }
    int i = 0;
    while (i < size) {
        int j = i + 1;
        while (j < size) {
            if (arr[i] == arr[j]) {
                // Shift elements to the left starting from the duplicate element
                for (int k = j; k < size - 1; k++) {
                    arr[k] = arr[k + 1];
                }
                // above loop starts with index of the duplicate element in the array.
                // Decrease the size of the array
                size--;
            } 
            j++;
        }
        i++;
    }

    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

4

12

4

1

Array without duplicates: 12 13 4 1

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