C Program to count duplicate / repeated elements in an array
C PROGRAM TO FIND COUNT OF DUPLICATE ELEMENTS IN AN ARRAY
In below program we will get the count of elements that are duplicated i.e. elements that are occurred more than once in an array.
Program Algorithm :
Step 1: Read size of array and store it in n
Step 2: If n (i.e size of array) is greater than MAX, print message and exit program
Step 3: Read elements of array and store in arr[MAX] , here MAX is a global variable whose value is 25 in the program below
Step 4: Initialize count = 0, to avoid garbage values
Step 5: Set i = 0
Step 6: Set j = i+1
Step 7: Check for duplicate, if arr[i] = arr[j] then increment count by 1 i.e. count = count + 1
Step 8: Increment j by 1 i.e. j = j + 1 and repeat Step 7 till j<n
Step 9: Increment i by 1 i.e. i = i + 1 and repeat Step 6-7 till i<n
Step 10: Print the count and exit program
Program :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
#include<stdio.h> #define MAX 25 //maximum size of array is 25 main() { int i,j,n,count,arr[MAX]; printf(" *** www.ProgrammingPosts.com ***"); printf("\n >>> C program to count duplicate elements in an array <<<"); //taking size of array as input from user printf("\n\n Enter the size of array: "); scanf("%d",&n); //checking if n value greater than MAX size of array if(n > MAX) { printf(" Max Array size allowed is %d",MAX); getch(); return; //terminates program execution } printf("\n Enter the %d elements of array: \n",n); //Reading the elements of array using for loop for(i=0;i<n;i++) { printf("\n arr[%d]:",i); scanf("%d",&arr[i]); } //initializing the count to 0, to avoid garbage value count =0; //Counting the duplicate elements in Array for(i=0; i<n; i++) { for(j=i+1; j<n; j++) { /* If duplicate found then increment count by 1 */ if(arr[i]==arr[j]) { count++; break; } } } printf("\n Count of duplicate elements in an array : %d\n",count); getch(); return 0; } |
Sample output :
*** www.ProgrammingPosts.com ***
>>> C program to count duplicate elements in an array <<<
Enter the size of array: 5
Enter the 5 elements of array:
arr[0]:10
arr[1]:20
arr[2]:30
arr[3]:10
arr[4]:20
Count of duplicate elements in an array : 2