C Programming (Turbo C++ Compiler) - Calculate Mode
I have given the simple C program for calculating mode for a set of numbers. The other related linkes are,
Calculate Mean
Calculate Median
Calculate Mode
Calculate Range
Calculate Variance
Calculate Standard Deviation
Source Code
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
typedef struct _Pair
{
int key;
int value;
} Pair;
typedef struct _Collection
{
Pair m_pair[100];
int m_maxElements;
} Collection;
const char* CalculateMode(float *arrValue, int max)
{
static char mode[256] = "";
char buf[32];
float value[100];
int i, j;
int highcount = 0;
float temp;
int nIndex = -1;
Collection map;
Pair ptemp;
memset(map.m_pair, 0, sizeof(Pair) * 100);
map.m_maxElements = 0;
if(max > 100)
return 0;
for(i = 0; i < max; i++)
value[i] = arrValue[i];
for(i = 0; i < max; i++)
{
for(j = 0; j < max - i - 1; j++)
{
if(value[j] > value[j + 1])
{
temp = value[j];
value[j] = value[j + 1];
value[j + 1] = temp;
}
}
}
for(i = 0; i < max; i++)
{
// Insert arrValue[i] to the map
nIndex = -1;
for(j = 0; j < map.m_maxElements; j++)
{
if(map.m_pair[j].key == value[i])
{
nIndex = j;
break;
}
}
if(nIndex == -1)
{
map.m_pair[map.m_maxElements].key = value[i];
map.m_pair[map.m_maxElements].value = 1;
map.m_maxElements++;
}
else
{
// map.m_pair[nIndex].key = value[i]; // alreday written
map.m_pair[nIndex].value++;
}
}
for(i = 0; i < map.m_maxElements; i++)
{
for(j = 0; j < map.m_maxElements - i - 1; j++)
{
if(map.m_pair[j].value < map.m_pair[j + 1].value)
{
ptemp = map.m_pair[j];
map.m_pair[j] = map.m_pair[j + 1];
map.m_pair[j + 1] = ptemp;
}
}
}
highcount = map.m_pair[0].value;
for(i = 0; i < map.m_maxElements; i++)
{
if(highcount == map.m_pair[i].value)
{
sprintf(buf, "%d ", map.m_pair[i].key);
strcat(mode, buf);
}
//std::cout << map.m_pair[i].key << " " << map.m_pair[i].value << "\n";
}
return mode;
}
int main()
{
float arrNumbers[100];
int i, max;
float mean;
const char *mode;
char buf[1024];
printf("Total Number of Elements: ");
scanf("%d", &max);
for(i = 0; i < max; i++)
{
printf("Enter [%d] Number: ", i + 1);
scanf("%f", &arrNumbers[i]);
}
printf("Total Numbers: %d\n", max);
mode = CalculateMode(arrNumbers, max);
printf("Mode: %s", mode);
return 0;
}
Output
Total Number of Elements: 10
Enter [1] Number: 6
Enter [2] Number: 7
Enter [3] Number: 8
Enter [4] Number: 7
Enter [5] Number: 6
Enter [6] Number: 5
Enter [7] Number: 2
Enter [8] Number: 2
Enter [9] Number: 9
Enter [10] Number: 3
Total Numbers: 10
Mode: 2 6 7
|