Finding the mode and variance.

I have come up with the following code, using Pseudonumber Generator. I need to use these generated numbers to figure out a couple of things (Mean, median, mode etc). (Yes this is part of my homework)

I can figure out the rest but I need help with 2 things. How can I use this code to figure out the mode, median and variance. Im not asking for a full code(although it would help).

I would like to create 3 functions, for each of the above purposes. I need a professional to explain to me where to go from here.

Thanks in advance.

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

// Proj 5.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>

int findVar(int, int, int);

int _tmain(int argc, _TCHAR* argv[])
{	int n;

printf ("Please enter an integer: ");
	scanf("%d", &n);
	while((n < 50) && (n > 0)){
		srand(n);
		if (n > 5)
			n=5;

		int i=0, v[50], sum = 0;
		float average;

		while (i < n){
			int x=rand() % 6;
			printf("%d: i=%d, n=%d\n", x, i, n);
			v[i]=x;
			sum = sum + x;
			i++;
		}
		
		average = (float) sum / n;
		// We have found the average, now we need to find median, and mode.

		printf ("v0= %d, v1 = %d, v2 = %d, v3 = %d, v4 = %d\nMean: %.2f\n\n",  v[0], v[1],v[2], v[3], v[4], average);
		
		scanf("%d", &n);
	}


	return 0;
}
Here's what you need to do. A function for median is included.

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
#include <iostream>	// for cout
#include <math.h>	// for floor

double mean(int* list, int num)
{
    double result=0;
    for(int i=0;i<num;++i)
        result+=list[i];
    return result/num;
};

double median(int* list, int num)
{
    if(floor(((double)num)/2) == (double)num/2)
        return ((double)list[num/2]+list[num/2-1])/2;
    return list[(int)floor(num/2)];
};

int main()
{
    int* numbers;
    numbers = new int[15];
    for(int i=0;i<11;++i)
        numbers[i] = i;
    numbers[11] = 10;
    numbers[12] = 11;
    numbers[13] = 12;

    std::cout << "Mean: " << mean(numbers, 14) << std::endl;
    std::cout << "Median: " << median(numbers, 14) << std::endl;

    return 0;
}
median: The median is the middle-most value in a sorted list. You have to sort your list in some order (ascending or descending; it does not matter), then access the middle value (if array has odd number of values) or average the two middle values (if array has
even number of values).

mode: The mode is the most common value. After sorting your array, count the number of occurrences of each value and pick
the one with the most number of occurrences.

variance: this just requires you to loop over all values and perform the math.
Topic archived. No new replies allowed.