Write C++ program to count total duplicate elements in an array

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.

#include <iostream>
using namespace std;
 
int main()
{
    int arr[100];
    int i, j, n, count = 0;
 
    // Readinng size of the array
    cout<<"Enter size of the array : ";
    cin>>n;
 
    //Reading elements of array
    cout<<"Enter elements in array : ";
    for(i=0; i<n; i++)
    {
        cin>>arr[i];
    }
    //Find all duplicate elements in array
    for(i=0; i<n; i++)
    {
        for(j=i+1; j<n; j++)
        {
        // If duplicate element found then increment count by 1
        if(arr[i] == arr[j])
            {
                count++;
                break;
            }
        }
    }
    cout<<"\nTotal number of duplicate elements found in array: "<<count;
 
    return 0;
}

Result

Write C++ program to count total duplicate elements in an array
Write C++ program to count total duplicate elements in an array

1 thought on “Write C++ program to count total duplicate elements in an array”

  1. #include
    using namespace std;

    int main()
    {
    int i, j, n, count = 0;

    // Readinng size of the array
    cout <> n;
    int arr[n];
    // Reading elements of array
    cout << "Enter elements in array : ";
    for (i = 0; i > arr[i];
    }
    int k = 1087654328;
    // Find all duplicate elements in array
    for (i = 0; i < n; i++)
    {
    for (j = i + 1; j < n; j++)
    {
    // If duplicate element found then increment count by 1
    if (arr[i] == arr[j] && arr[i]!=k)
    {
    count++;
    k = arr[i];
    break;
    }
    }
    }
    cout << "\nTotal number of duplicate elements found in array: " << count;

    return 0;
    }

    Reply

Leave a Comment