C program for finding repeating element in an array

Repeating element of an array

In this section, we will learn the  Program to Find the Elements that have Duplicates or we will be finding Repeating element of an array.

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.

Given an array, print all element whose frequency is one.

Example

Input: a[]= { 1,2,5,2,6,7,5 }

Output: 2,5

There is two number which has more than one frequency.

so there is two number which is repeated.

Repeating elements in an array in C

 Algorithm

Step 1. Input the size of array from the user.

Step 2. Input the elements of array from the user.

Step 3. Count the frequency of each element, if it is more than 2 then sent it to new array

Step 4. Print the elements of new array

C Program

 

#include   
int main()  
{
    int n, i , j, count=0, unique = 0;;
   // Taking size of array as input from the user
printf("enter size : ");
    scanf("%d",&n);
    int arr[n];
    int newarr[n];
// Taking the elements of the array as input
    printf("enter elements : ");
    for(i=0; i<n; i++)
    {
        scanf("%d",&arr[i]);
    }
// Checking for the repeating elements in an array
    for(i=0; i<n; i++)
    {
        count = 0;
       for(j=0;j<=i;j++)
        {
            if(arr[i]==arr[j])
            {
                count++;
            }
        }
        if(count>1)
        {
            newarr[unique] = arr[i];
            unique++;
        }
    }
// Printing the elements of the array which is repeating
    printf("The Repeating Element of array are : ");
    for(i=0; i<unique; i++)
    {
        printf("%d ",newarr[i]);
    }
    return 0;

Output :-

Enter size of an array
6
Enter elements in an array
12
2
12
3
9
2
The repeating elements are
2,12

//Test case 2

 Enter elements in an array
 12
 22
 12
 33
 99
 22
 The repeating elements are 22,12, 33

//Test case 3

Enter elements in an array
22
22
22
33
77
22
The repeating elements are
22,33,77