C program count total number of duplicate elements in an array

Write a C program to read elements in an array from user and count total number of duplicate elements in array. C program to find all duplicate elements in an unsorted array. How to list all duplicate elements in an unsorted array using loop in C programming.

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, Array

Algorithm to count total duplicate elements in array

Step 1: Set count = 0
Step 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


Happy coding ;)


You may also like

Labels: , ,