One of my homeworks required me to create 30 random numbers from 0 - 9 and count how many times each number appeared.
I made a long if-else statement to check each number condition (as can be seen on the code). I'm just wondering if there is a much faster way to do this?
I need to show which number appeared the most and how many times, however when I compile my program, the max number which appears and the min number doesn't show. What's wrong with my condition statement?
#include <ctime>
#include <iostream>
#include <iomanip>
#include <array>
usingnamespace std;
void Display(int *x);
void DisplayData(int *x);
void FindMaxMin(int *x);
struct NUM
{
int n;
int freq;
};
NUM ALL[10];
int main()
{
srand(time(0));
int random[30];
for (int i = 0; i < 30; i++) //assign random numbers 0-9 to n
{
random[i] = rand() % 10;
}
Display(random); // show the random numbers assigned
cout << endl;
for (int i = 0; i < 10; i++) //set all numbers to integers from 0 - 9
{
ALL[i].n = i;
}
for (int i = 0; i < 30; i++)
{
ALL[random[i]].freq++;
}
DisplayData(random); //display the random numbers and their frequency
FindMaxMin(random);
system("PAUSE");
return 0;
}
void Display(int *x)
{
for (int i = 0; i < 30; i++)
{
cout << i[x] << " ";
}
}
void DisplayData(int *x)
{
cout << "\tNUMBER \tFREQUENCY" << endl;
for (int i = 0; i < 30; i++)
{
cout << char(196);
}
cout << endl;
cout << setfill(' ');
cout << fixed << showpoint << setprecision(2);
for (int i = 0; i < 10; i++)
{
cout << left << setw(10) << ALL[i].n << right << setw(10) << ALL[i].freq;
cout << endl;
}
}
void FindMaxMin(int *x)
{
int max = 0;
int min = 9;
for (int i = 0; i < 10; i++)
{
if (ALL[i].freq > max)
{
max = ALL[i].freq;
if (x[i] == max)
{
cout << "Number(s) with the largest frequency of " << max << " is/are: " << x[i] << endl;
}
}
if (ALL[i].freq < min)
{
min = ALL[i].freq;
if (x[i] == min)
{
cout << "Number(s) with the lowest frequency of " << min << " is/are: " << x[i] << endl;
}
}
}
}