count how many times elements in an array are repeated

Hello! I want to know how I can count how many times elements are repeated in an array. This is what I've done:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include<iostream>
using namespace std;
void main()
{
  int a[5];
  int b[5];
  int p;
  int i;
   
  for (p=0; p<5; p++){
     cout<<"Enter the numbers ";
     cin>>a[p];
  }
  int flag=1;
  int temp;
  int j;
  for(i = 0; (i <5) && flag; i++)
     {
          flag = 0;
          for (j=0; j < 4; j++)
         {
               if (a[j+1] < a[j]) 
	  { 
                    temp = a[j];             
                    a[j] = a[j+1];
                    a[j+1] = temp;
                    flag = 1;
			   }
      }
  }
  
  b[0]=a[0];
  int d,m=1;
  for(d=1;d<5;d++)
  {
	  if(a[d]!=a[d-1])
	  {
		  b[m]=a[d];
		  m++;
	  }
  }
  
	  
  cout<<"Numbers are"<<b[0];
  for(i=1;i<m;i++)
	  cout<<b[i];
  


}
use std::count
http://www.cplusplus.com/reference/algorithm/count.html

for(int i = 0; i < 5; ++i)
{
std::cout << a[i] << "was repeated " << std::count(a, a + 5, a[i]) << " times. " << std::endl;
}

I'm not sure what your 2nd and 3rd for loops are doing. I would just start over and use std::count. The only thing left for you to figure out is to determine how to avoid repeating the same text over and over. I just posted that to show how std::count can help simplify your program.
Last edited on
Thanks for the help. I want to know if there's another way to count the elements without using a function.Another more simple way. I'm using the second loop for to sort the array. I'm a beginner.
Last edited on
I still haven't learnt how to use functions. Definitely they'll simplify the programs. Is there any way to count the elements with loops.
Use a loop to go through the array looking for elements and adding 1 to a counter every time that element is found.
"Thanks for the help. I want to know if there's another way to count the elements without using a function.Another more simple way. I'm using the second loop for to sort the array. I'm a beginner."

I don't know how to answer this. How is writing your own loop simpler than calling a function that does the work for you?
Topic archived. No new replies allowed.