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 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
|
#include <dos.h>
#include <stdlib.h>
#include <conio.h>
#include <iostream.h>
#include <fstream.h>
void displayarr (int* arr, int n);
float calculateMean (int* arr,int n);
void sort (int* arr, int n);
float calculatemedian(int* arr, int n);
float calculatemode (int* arr, int n);
void main()
{
clrscr();
unsigned int n;
int* arr;
//ifstream fin;
//ofstream fout;
//fout.open("assignment.txt");
cout << "Enter the size of the array: ";
//fin.open("assignment.txt");
cin >> n;
arr = new int[n];
srand(time(0));
int i=0;
do
{
arr[i] = rand() % 9+4;
cout << "The random numbers generated are: " << arr[i] <<endl;
i++;
}
while (i<n);
/*for (int i=0;i<n;i++)
arr[i] = rand() % 9 + 4;*/
cout << "The numbers in the array is: \n";
displayarr (arr, n);
float mean = calculateMean (arr, n);
sort (arr, n);
cout << "The mean is: " << mean << endl;
float median = calculatemedian (arr, n);
cout << "The median is: " << median <<endl;
float mode = calculatemode (arr, n);
cout << "The mode is: " << mode <<endl;
getch();
//fout.close();
//fin.close();
}
float calculateMean (int *arr, int n)
{
float total = 0;
for (int i=0;i<n;i++)
total = total+arr[i];
return (total/n);
}
void sort (int* arr, int n)
{
for (int i =0; i<n-1; i++)
{
for (int j=i+1; j<n; j++)
{
if (arr[j] <arr[i])
{
int temp = arr[j];
arr [j] = arr [i];
arr [i] = temp;
}
}
}
}
void displayarr (int* arr, int n)
{
for (int i=0; i<n; i++)
cout << arr[i] << "\t";
cout << endl;
}
float calculatemedian(int* arr, int n)
{
float median;
if (n%2 == 0)
{
median = (float) (arr[n/2] + arr[n/2-1])/2;
}
else
{
median = arr[(n-)1/2];
}
return (median);
}
float calculatemode (int* arr, int n)
{
int freqtable[9] = {0,0,0,0,0,0,0,0,0};
for(int i=0; i<n; i++)
{
++(freqtable [arr[i]-4]);
}
int indexlargest=0;
int largest = arr[0];
for (int a=1; a<n; a++)
{
if (arr[a] > largest)
{
indexlargest =i;
largest =arr[a];
}
}
return (indexlargest+4);
}
|