Random number array help1

I need to create 20 random numbers and find how many times each number pops up.

for example, if the integer 20 appears 4 times, the frequency would be 4.

I am having trouble where it is not inputting the correct frequency, instead it just shows a numerical value which is unassociated with the actual appearance of the integer.

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
#include <iostream>
#include <array>
#include <ctime>

using namespace std;

int main()
{
	int random[20];
	int freq;
	freq = 0;
	srand(time(0));

	cout << "Here are the 20 randomly generated numbers from 20-30: " << endl;
	cout << "N\t\t Freq: " << endl;
	for (int i = 0; i < 20; i++)
	{
		random[i] = (rand() % 10) + 20;

		if (random[i] == 20)
		{
			freq++;
		}
		if (random[i] == 21)
		{
			freq++;
		}
		if (random[i] == 22)
		{
			freq++;
		}

		cout << random[i] << "\t\t" << freq << endl;
	}

	

	system("PAUSE");
	return 0;
}
Your approach is not correct.
Your freq sums up the frequencies of 20,21 and 22 which is not correct.
What about the other values.

Try this
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
#include <iostream>
#include <ctime>
#include <algorithm>
#include <iterator>
#include <vector>
using namespace std;

int main()
{
	int n = 20;
	vector<int> random;

	//fill the array
	for(int i = 0; i < n; i++)
		random.push_back(rand()%10 + 20);

	//print the array
	copy(random.begin(),random.end(),ostream_iterator<int>(cout," "));
	cout<<endl;

	//max random number
	int max = *max_element(random.begin(),random.end());
	vector<int> freq(max + 1);	//array of frequencies

	//fill freq vector
	for(int i = 0; i < random.size(); i++)
		++freq.at(random.at(i));
	
	//print frequencies
	cout<<endl;
	for(int i = 0; i < freq.size(); i++)
		if(freq.at(i) != 0)
			cout<<i<<"-"<<freq.at(i)<<endl;

	cout<<endl;
	cin.ignore();

	return 0;
}
I cannot use vectors or iterators as we have not studied them yet, it has to be a lot simpler.
You can use arrays if you want.
Just follow the same idea.
Topic archived. No new replies allowed.