# Repeating Elements in an array using C++

## Find Repeating Elements In An Array

An element in an array which is repeated more than once in the given array is called a Duplicate element.
For finding  Repeating Elements in an array using C++ 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

## 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.

## Method 1 ​:-

```#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=0; i<s; i++)  // input elements of an array     {           cin >> arr[i];
}
cout << “Duplicate elements are :” << endl;
for(int i=0; i<s–1; i++) // loop to traverse array
{
for(int j=i+1; j<s; j++) // 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```

## Output

```Enter size of array :
6
Enter elements of array :
5 4 3 1 1
Duplicate elements are :
5 4 3 1```

## Method 2:-

```#include <bits/stdc++.h>
using namespace std;
//Checking westher the elements is already present
bool alreayPresent(vector v, int val) {
for(auto item : v) {
if(item == val)
return true; //if the item is equal to value then return true
}

return false; //otherwise return false
}

void repeatingElements(int arr[], int n) {
vector v;

for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
if(arr[i] == arr[j] && !alreayPresent(v, arr[i])) {
cout << arr[i] << " "; //printing distinct element in an array v.push_back(arr[i]);       }    } } } int main() {    int n; cin >> n;

int arr[n];//Taking input array from the user
for(int i = 0; i < n; i++) cin >> arr[i];

repeatingElements(arr, n);
return 0;
}```
```Output-
1 2 4 2 1 2 1 4
Output-
1 2 4```
```Output-
2 4 5 6 1 1 2 4 5Output-
2 4 5 6 1```