Repeating Elements in an array using C++

Finding all Duplicates in the given array using C++

An element in an array which is repeated more than once in the given array is called a Duplicate element.
To find the repeated elements in an array we require two loops. One will be used for array traversal and the other one is used for comparing the current element with all other elements of the array.

Sample Test Case

Enter the size of array : 5
Enter elements of array : 5 8 7 8 5
Output
Duplicate elements : 5 8

Finding Repeating Elements in Array using C++

Algorithm

  1. Start.
  2. Declare size of array.
  3. Declare array.
  4. Input elements of the array.
  5. Take a for loop to traverse the whole array.
  6. Take another for loop to compare the current index element to all other elements after it. Note : index i should not be equal to index j.
  7. Print the Duplicate elements.
  8. End.

C++ Code

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int s; // declare size of array
    
    cout << “Enter size of array :” << endl;
    
    cin >> s;
    
    int arr[s]; // declare array
    
    cout << “Enter elements of array :” << endl;
    
    for(int i=0i<si++)  // input elements of an array
    {
        cin >> arr[i];
    }
    
    cout << “Duplicate elements are :” << endl;
    
    for(int i=0i<s1i++) // loop to traverse array
    {
        for(int j=i+1j<sj++) // loop to compare elements 
        {
            if(arr[i]==arr[j] && i!=j) // compare duplicates when i not equals j
              cout << arr[i] << ” “;
        }
    }
    
    return 0;
}


Output

Enter size of array :                                                                                                     
5   

Enter elements of array :                                                                                                 
5 8 7 8 5  

Duplicate elements are :                                                                                                  
5 8                                                                                                                       

This page is contributed by Rishav Raj