﻿ C exercises: Count a total number of duplicate elements in an array - w3resource

# C Exercises: Count a total number of duplicate elements in an array

## C Array: Exercise-5 with Solution

Write a program in C to count a total number of duplicate elements in an array.

Pictorial Presentation: Sample Solution:

C Code:

``````#include <stdio.h>

void main()
{
int arr1;
int arr2;
int arr3;
int n,mm=1,ctr=0;
int i, j;

printf("\n\nCount total number of duplicate elements in an array:\n");
printf("---------------------------------------------------------\n");

printf("Input the number of elements to be stored in the array :");
scanf("%d",&n);

printf("Input %d elements in the array :\n",n);
for(i=0;i<n;i++)
{
printf("element - %d : ",i);
scanf("%d",&arr1[i]);
}
/*----------------- copy in other array ------------------------------------*/
for(i=0;i<n; i++)
{
arr2[i]=arr1[i];
arr3[i]=0;
}
/*------------------- mark the elements are duplicate -------------------------*/
for(i=0;i<n; i++)
{
for(j=0;j<n;j++)
{
if(arr1[i]==arr2[j])
{
arr3[j]=mm;
mm++;
}
}
mm=1;
}
/*--------------- Prints the array ------------------------------------*/
for(i=0; i<n; i++)
{
if(arr3[i]==2){ctr++;}
}
printf("The total number of duplicate elements found in the array is: %d \n", ctr);

printf("\n\n");
}
```
```

Sample Output:

```Count total number of duplicate elements in an array:
---------------------------------------------------------
Input the number of elements to be stored in the array :3
Input 3 elements in the array :
element - 0 : 5
element - 1 : 1
element - 2 : 1

Total number of duplicate elements found in the array is : 1
```

Flowchart: C Programming Code Editor:

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

﻿

Inviting useful, relevant, well-written and unique guest posts