This program will generate random number from 1 to 100. It depends on how many number you would like to generate. You can enter 500, then it will generate 500 random number from 1 to 100. My problem is: how can i count how many 1's, 2's, 3's, ....., 100's. And the number are sorted already. Here is my code:
#include <stdafx.h>
#include <iostream>
using namespace std;
void fillArray (int a[], int size, int& numberused);
void sort (int a[], int numberused);
void swapValues (int& v1, int& v2);
int indexOfSmallest (const int a[], int startIndex, int numberused);
int main ()
{
const int max=100000;
int arr[max], numberused;
fillArray (arr, max, numberused);
sort (arr, numberused);
cout<<"In sorted orded the numbers are:\n";
for (int index=0; index<numberused; index++)
cout<<arr[index]<<" ";
cout<<endl;
return 0;
}
void fillArray(int a[], int size, int& numberused)
{
int index=0;
cout<<"How many random number you would like to generate? ";
cin>>size;
for (index=0; index<size; index++)
{
a[index]=rand()%100+1;
}
numberused=index;
}
void sort (int a[], int numberused)
{
int indexONextfSmallest;
for (int index=0; index<numberused-1; index++)
{
indexONextfSmallest=indexOfSmallest(a, index, numberused);
swapValues(a[index], a[indexONextfSmallest]);
}
}
int indexOfSmallest (const int a[], int startIndex, int numberused)
{
int min=a[startIndex], indexOfMin=startIndex;
for (int index=startIndex+1; index<numberused; index++)
if(a[index]<min)
{
min=a[index];
indexOfMin=index;
}
return indexOfMin;
}
To count the frequencies use an array int my_frequency_array[100] = {0}; and a loop to increment a proper value for(int i = 0; i < numberused; i++) my_frequency_array[ arr[i] ]++;.
To improve your current code you could use vector instead of array, and sort() from algorithm.h instead of the one you're using now.
Good luck