Q:

Write C++ program to count number of each element in an array

0

Write C++ program to count number of each element in an array

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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], frequency[100];
    int i, j, count, num;
 
    //Enter size of array
    cout<<"Enter size of array: ";
    cin>>num;
 
    //Reading elements of array
    cout<<"Enter elements in array: ";
    for(i=0; i<num; i++)
    {
       cin>>arr[i];
 
        //Initially initialize frequency variable to -1
        frequency[i] = -1;
    }
 
     for(i=0; i<num; i++)
    {
        count = 1;
        for(j=i+1; j<num; j++)
        {
        //If duplicate element is found
        if(arr[i]==arr[j])
            {
                count++;
 
                //Make sure not to count frequency of same element again
                frequency[j] = 0;
            }
        }
 
        //If frequency of current element is not counted
        if(frequency[i] != 0)
        {
            frequency[i] = count;
        }
    }
 
    //Print frequency of each element
    cout<<"\nFrequency of all elements of array : \n";
    for(i=0; i<num; i++)
    {
      if(frequency[i] != 0)
        {
            cout<<arr[i]<<" occurs "<<frequency[i]<<" times\n";
        }
    }
 
       return 0;
}

Result:

Enter size of array: 5

Enter elements in array: 1

2

3

1

2

Frequency of all elements of array : 

1 occurs 2 times

2 occurs 2 times

3 occurs 1 times

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Write C++ program to delete all duplicate elements... >>
<< Write C++ program to copy all elements of one arra...