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


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


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

Introduction

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


  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. int arr[100], frequency[100];
  7. int i, j, count, num;
  8.  
  9. //Enter size of array
  10. cout<<"Enter size of array: ";
  11. cin>>num;
  12.  
  13. //Reading elements of array
  14. cout<<"Enter elements in array: ";
  15. for(i=0; i<num; i++)
  16. {
  17. cin>>arr[i];
  18.  
  19. //Initially initialize frequency variable to -1
  20. frequency[i] = -1;
  21. }
  22.  
  23. for(i=0; i<num; i++)
  24. {
  25. count = 1;
  26. for(j=i+1; j<num; j++)
  27. {
  28. //If duplicate element is found
  29. if(arr[i]==arr[j])
  30. {
  31. count++;
  32.  
  33. //Make sure not to count frequency of same element again
  34. frequency[j] = 0;
  35. }
  36. }
  37.  
  38. //If frequency of current element is not counted
  39. if(frequency[i] != 0)
  40. {
  41. frequency[i] = count;
  42. }
  43. }
  44.  
  45. //Print frequency of each element
  46. cout<<"\nFrequency of all elements of array : \n";
  47. for(i=0; i<num; i++)
  48. {
  49. if(frequency[i] != 0)
  50. {
  51. cout<<arr[i]<<" occurs "<<frequency[i]<<" times\n";
  52. }
  53. }
  54.  
  55. return 0;
  56. }
  57.  

Result

C++ language techstudy.org

     





Related Topics




Popular Posts