Find the frequency of each element in a sorted array | C ++ program for the above approach ; Function to print the frequency of each element of the sorted array ; Stores the frequency of an element ; Traverse the array arr [ ] ; If the current element is equal to the previous element ; Increment the freq by 1 ; Otherwise , ; Update freq ; Print the frequency of the last element ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void printFreq ( vector < int > & arr , int N ) { int freq = 1 ; for ( int i = 1 ; i < N ; i ++ ) { if ( arr [ i ] == arr [ i - 1 ] ) { freq ++ ; } else { cout << " Frequency ▁ of ▁ " << arr [ i - 1 ] << " ▁ is : ▁ " << freq << endl ; freq = 1 ; } } cout << " Frequency ▁ of ▁ " << arr [ N - 1 ] << " ▁ is : ▁ " << freq << endl ; } int main ( ) { vector < int > arr = { 1 , 1 , 1 , 2 , 3 , 3 , 5 , 5 , 8 , 8 , 8 , 9 , 9 , 10 } ; int N = arr . size ( ) ; printFreq ( arr , N ) ; return 0 ; }