Program to find repeating element in an array (duplicate elements)

An easier approach to find all repeating elements in an array is to use two loops. Use the first loop for traversing the array and the second loop to check if the current element is already encountered.

Algorithm

  1. Declare the array and input the array elements
  2. Start traversing the array and check if the current element is already encountered
  3. If it is already encountered, print the element as a repeating element and continue
  4. If not, move to the next element of the array and continue
#include<stdio.h>
void repeating_element(int arr[], int n)
{
int i, j;
int count = 0;
printf("Repeating elements are: ");
for(i = 0;i < n;i++)
{
for(j = i+1;j < n;j++)
{
if(arr[i] == arr[j])
{
printf("%d ", arr[j]);
}
}
}
}
int main()
{
int n;
scanf("%d",&n);
int arr[n];
int i;
for(i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
}
repeating_element(arr,n);
return 0;
}
#include <iostream>
#include <stdlib.h>
using namespace std;
void repeating_element(int arr[], int n)
{
int i, j;
int count = 0;
printf("Repeating elements are: ");
for(i = 0;i < n;i++)
{
for(j = i+1;j < n;j++)
{
if(arr[i] == arr[j])
{
cout << arr[j] << " ";
}
}
}
}
int main()
{
int n;
cin >> n;
int arr[n];
int i;
for(i = 0; i < n; i++)
{
cin >> arr[i];
}
repeating_element(arr,n);
return 0;
}

Test case:

  • Input: 1 2 3 1 2

Output:
Repeating elements are: 1 2