Example:
If the elements of array are: 1, 10, 20, 1, 25, 1, 10, 30, 25, 1
Total number of duplicate elements = 5
Duplicate elements in array are : 1, 1, 1, 10, 25
Required knowledge
Basic C programming, If else, For loop, Nested loop, ArrayAlgorithm to count total duplicate elements in array
Step 1: Set count = 0Step 2: Set i = 0
Step 3: Set j = i+1
Step 4: Check if array[i] == array[j] then increment count by 1 i.e. count = count + 1
Step 5: Increment j by 1 i.e. j = j + 1 and repeat Step 4-5 till j<n (Where n is the total number of elements in array.
Step 6: Increment i by 1 i.e. i = i + 1 and repeat Step 3-5 till i<n.
Program to count total duplicate elements in an array
/* * C program to count total number of duplicate elements in an array */ #include <stdio.h> int main() { int arr[100]; int i,j, n, count = 0; /* * Reads size and elements of array */ printf("Enter size of the array : "); scanf("%d", &n); printf("Enter elements in array : "); for(i=0; i<n; i++) { scanf("%d", &arr[i]); } /* * Finds all 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("\nTotal number of duplicate elements found in array = %d", count); return 0; }
Output
Enter size of the array : 10
Enter elements in array : 1 10 20 1 25 1 10 30 25 1
Total number of duplicate elements found in array = 5
Enter elements in array : 1 10 20 1 25 1 10 30 25 1
Total number of duplicate elements found in array = 5
Happy coding ;)
You may also like
- Array and Matrix programming exercises index.
- C program to find maximum and minimum elements in an array.
- C program to insert an element in an array at specified position.
- C program to delete and element from array at specified position.
- C program to delete all duplicate elements from an array.
- C program to find all unique elements in an array.
- C program to count total number of even and odd elements in an array.
- C program to merge two array to a third array.
- C program to count frequency of each element of an array.
- C program to sort elements of array in Ascending order.