count occurrence in c++ array

I must count the number of occurrence of all numbers in array , i wrote a code but it does not work properly
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
#include <iostream>
int main (){
	int i,n,tmp,counter=0;
	std::cout<<"Enter the size of the array:"<<std::endl;
	std::cin>>n;
	int *Array=new int [n];
	int *counterArray=new int [n];
	int *indexCounterArray=new int [n];
	for ( i=0;i<n;i++){
		std::cin>>Array[i];

	}
	for ( int j=1;j<n;j++){
	for ( i=0;i<n-1-j;i++){
		if (Array[i]>Array[i+1]){
			tmp=Array[i];
			Array[i]=Array[i+1];
			Array[i+1]=tmp;
	}
		
	}
	
	}
	
	for (int j=0;j<n-1;j++){
		if (Array[i]==Array[j]){
			counter++;
			indexCounterArray[j]=counter;
		}
		}
	for (int b=0;b<n;b++){
		std::cout<<counterArray[b]<<"\t"<<indexCounterArray[b];
	}
	return 0;
}
closed account (o3hC5Di1)
Hi there,

Welcome to the forums. When your code isn't behaving as you expect it to, please be a little bit more specific about your problem. Does it compile? Does it crash? Which compilation or crash error messages are you getting? If your program behaves different from what you expect, tell us what you expect and what it actually does. That helps us to help you better.

Regarding your code: On line 26 you do:

if (Array[i]==Array[j])

i is always going to be whatever state it is in after the last loop of line 14:

for ( i=0;i<n-1-j;i++)

So you Array[i] will always be the same number - is that what you want?

If you need any more help, please be a little bit more specific and we'll be happy to help you along.

All the best,
NwN
You do a sort in 13-23. Was that required too?

What do you know about the range of the input values?

You are not allowed to use std::map, are you?

You print counterArray before initializing values.

You don't deallocate heap at exit.
Topic archived. No new replies allowed.