#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void sortArr(int[]); // Sort the array in ascending order
void printArr(int[]); // Displaying the array on the screen
void printMean(int[]);
void printMedian(int[]);
void printMode(int[]);
int main()
{
int arr[20];
char key;
srand(time(0)); // Initialization of the random number generator
cout << "Initial array: ";
for(int i=0;i<20; i++) // Fill the array with random numbers from the range from 10 to 90
{
arr[i]=(int)rand()%81+10;
cout << arr[i]; // Control output on the screen
cout << ' ';
}
cout << endl;
sortArr(arr); // Sort the array in ascending order.
// printArr(arr); You can display the array after sorting.
/* Menu */
do{
cout << endl;
cout << "<W> Mean" << endl;
cout << "<E> Median" << endl;
cout << "<R> Mode" << endl;
cout << "<Q> Quit" << endl;
key = cin.get();
cin.get();
switch (key)
{
case 'W':
case 'w': printMean(arr); break;
case 'E':
case 'e': printMedian(arr); break;
case 'R':
case 'r': printMode(arr); break;
}
}while(!(key=='q')||(key=='Q'));
return 0;
}
/*Standard algorithm for sorting the array in ascending order.*/
void sortArr(int *arr)
{
int i,j,k;
for(i=0; i<19; i++)
{
for(j=i+1; j<20; j++)
{
if(arr[i]>arr[j])
{
k=arr[i];
arr[i]=arr[j] ;
arr[j]=k;
}
}
}
};
/*Auxiliary function for displaying the array on the screen. You don't need to use it.*/
void printArr(int *arr)
{
cout << "Array: ";
for(int i=0;i<20; i++)
{
cout << arr[i];
cout << ' ';
}
cout << endl;
};
/*Mean*/
void printMean(int *arr)
{
int summ = 0;
for(int i=0; i<19; i++) summ+=arr[i];
cout << "Mean = " << summ/20 << endl;
};
/*Median*/
void printMedian(int *arr)
{
/*The array is sorted. Output the average value arr[9] arr [10] .*/
cout << "Median = " << (arr[9]+arr[10])/2 << endl;
};
/*Mode*/
void printMode(int *arr)
{
int num=-1; // Repetitive number in the array.
int maxNumCount=0; // Maximum number of repetitions.
int numCount=0; // The number of repetitions of the current array element.
int i,j;
/*Determine the maximum number of repetitions in the array.*/
for(i=0; i<19; i++)
{
numCount=0;
for(j=i+1; j<20; j++)
{
if(arr[i]==arr[j])
{
numCount++;
}
}
if(numCount>maxNumCount)
{
maxNumCount=numCount;
num=arr[i];
}
}
/* If there are no repetitions, we display a message: "No modes" */
/* If there are repetitions, we print the numbers that are repeated as many times as possible.*/
if(num > -1)
{
cout << "Mode = ";
for(i=0; i<19; i++)
{
numCount=0;
for(j=i+1; j<20; j++)
{
if(arr[i]==arr[j])
{
numCount++;
}
}
if(numCount==maxNumCount)
{
cout << arr[i] << ' ';
}
}
cout << endl;
}
else cout << "No modes" << endl;
};
Comments
Leave a comment