adsense

Hii, welcome to my site. My name is Om prakash kartik. This blog helps you to learn programming languages concepts.

Program in C++ to count frequency of each elements of array, string

Program in  C++ to count frequency of each elements of array, string

  • Count each elements of array, string 
  • Function are created using template concept
#include<iostream>
#include<string.h>
 using namespace std;
 template <class T>
 void deletePos(T *arr, int &n, int pos){
    for(int i = pos; i < n - 1; i++){
        arr[i] = arr[i + 1];
    }
    n--;
 }
 template <class T>
 void copy(T *newA, T *oldA, int n){
     for(int i = 0; i < n; i++)
        newA[i] = oldA[i];
 }
 template <class T>
 void frequency(T *arr, int n){
    T item[n], a[n];
    int freq[n];
    int count, i;
    copy<T>(a, arr, n);
    for(i = 0; i < n; i++){
        count = 1;
        for(int j = i + 1; j < n; j++){
            if( a[i] == a[j]){
                count++;
                deletePos<T>(a,n,j);
                j--;
            }
        }
        item[i] = a[i];
        freq[i] = count;
    }
    for(i = 0; i < n; i++){
      cout<<"\nFrequency of "<<item[i]<<" : "<<freq[i];
   }
 }
 int main()
  {
    int arr[] = {29,40,11,30,11,20,20,30,40,38,10,11,30,33};
    int n = 14;
    cout<<"Elements of array is : ";
    for(int i = 0; i < n; i++)
        cout<<"   "<<arr[i];
    frequency<int>(arr,n);
    // for String
    char *str = "Programming.OM";
    cout<<"\n\nstr : "<<str;
    frequency<char>(str,strlen(str));
    return 0;
  }
Output :-




Related Programs

  • Program in C & C++ to count frequency of each letter in a string

Post a Comment

0 Comments