Array elements that appear more than once in C?

CObject Oriented ProgrammingProgramming

Array is a container of elements of Same data types length needs to be defined beforehand. And an element can appear in any order and any number of times in an array. so in this program we will find elements that appear more than once in an array.

Problem description − We have given an array arr[] in which we have to find which of the element are repeating in the array an app to print them.

Let’s take an example to understand this better.

Example,

Input: arr[] = {5, 11, 11, 2, 1, 4, 2}
Output: 11 2

Explanation

We have an array arr which contains some element firstly we would compare the element from the next element in the duplicate function which is used to find the repeated element in the array. In duplicate function we are using the loop to find the duplicate elements in the given array we will use if else condition to check the count of array elements from the array element occurred one time then the count will be 1 if occur more than one time then count will be incremented respectively if the count is more than 1 then the element will be printed on the screen.

Algorithm

Input : arr[], n the length of array.
Step 1 : For i -> 0 to n, Follow step 2,
Step 2 : For each element of the array. Do :
   Step 2.1 : For j -> i to n repeat step 2.2 - 2.3.
   Step 2.2 : if (arr[i] == arr[j]) -> print arr[i]
   Step 2.3 : else {// do nothing}

Example

#include <stdio.h>
int main() {
   int arr[] = {21, 87, 212, 109, 41, 21};
   int n=7;
   printf("The repeat elements of the array are : ");
   int *count = (int *)calloc(sizeof(int), (n - 2));
   int i;
   for (i = 0; i < n; i++) {
      if (count[arr[i]] == 1)
         printf(" %d ", arr[i]);
      else
         count[arr[i]]++;
   }
   return 0;
}

Output

The repeat elements of the array are : 21
raja
Published on 04-Oct-2019 11:41:31
Advertisements