C++ Program to find duplicate elements in the array


In this program, You will learn how to find duplicate elements in array in C++.


List is: 1, 2, 12, 23, 12, 23

Duplicate elements are: 12 23

Example: How to find duplicate elements in an array in C++.

#include<iostream>
using namespace std;

int main() {

    int i, j, n, v = 1;
    int arr[100];

    cout << "Enter size of an array:";
    cin>>n;
    cout << "Enter array elements:";
    for (i = 0; i < n; i++) {
        cin >> arr[i];
    }

    cout << "Duplicate elements:";
    for (i = 0; i < n; i++) {
        for (j = i + 1; j < n; j++) {
            if (arr[i] == arr[j]) {
                if (v == 1 && arr[j] != '\0') {
                    cout << arr[i] << " ";
                }
                arr[j] = '\0';
                v++;
            }
        }
        v = 1;
    }

    return 0;
}

Output:

Enter size of an array:5
Enter array elements:30 40 30 12 12
Duplicate elements:30 12