My code is below. I have a program that compiles and works, I just have a few problems with it. the mode method isn't working, and the median doesn't work either. if the user enters 4 (to enter 4 integers) the median will be the 2 middle numbers average. so if the numbers are : 1 4 5 30, the median would be 4.5000. also, my goAgain() method doesn't work, and I dont know why. I want to ask the user if he / she wants to play again, enter y or Y for yes and n or N for no, but even if they do enter those letters, it just goes "invalid, try again" and never works right. PLEASE HELP!!! thank you
Code:
#define MAX 25
#include<stdio.h>
#include <stdbool.h>
#include <time.h>
#include <stdlib.h>
int readTotalNums();
void fillArray(int total, int nums[]);
void sortArray(int nums[], int total);
double findMean(int nums[], int total);
double findMedian(int nums[], int total);
int findMode(int nums[], int total);
void printResults(double mean, double median, double mode);
bool goAgain();
int main() {
int nums[MAX];
int total;
double mean, median, mode;
do {
total = readTotalNums();
fillArray(total, nums);
sortArray(nums, total);
mean = findMean(nums, total);
median = findMedian(nums, total);
mode = findMode(nums, total);
printResults(mean, median, mode);
} while (goAgain()==true);
return 0;
}
int readTotalNums() {
int num;
do {
printf("How many numbers? ");
scanf("%i", &num);
} while (num < 1 || num > 25);
return num;
}
void fillArray(int total, int nums[]) {
int temp;
int i;
printf("Please enter %i numbers\n", total);
for (i = 0; i <= total-1; i++) {
scanf("\n%i",&nums[i]);
}
}
void sortArray(int nums[], int total) {
int x;
int y;
for(x=0; x<total; x++) {
for(y=0; y<total-1; y++) {
if(nums[y]>nums[y+1]) {
int temp = nums[y+1];
nums[y+1] = nums[y];
nums[y] = temp;
}
}
}
}
double findMean(int nums[], int total) {
int i;
double sum = 0.0;
for(i = 0; i < total; i++) {
sum += nums[i];
}
return (sum/total);
}
double findMedian(int nums[], int total) {
int temp;
int i,j;
for(i=0;i<total;i++)
for(j=i+1;j<total;j++) {
if(nums[i]>nums[j]) {
temp=nums[j];
nums[j]=nums[i];
nums[i]=temp;
}
}
if(total%2==0) {
int x;
int y;
x = nums[total/2];
y = nums[(total/2) - 1];
return ((x+y)/2);
}else {
return nums[total/2];
}
}
int findMode(int nums[],int total) {
int i, j, maxCount, modeValue;
int tally[total];
for (i = 0; i < total; i++) {
tally[nums[i]]++;
}
maxCount = 0;
modeValue = 0;
for (j = 0; j < total; j++) {
if (tally[j] > maxCount) {
maxCount = tally[j];
modeValue = j;
}
}
return modeValue;
}
void printResults(double mean, double median, double mode) {
printf("Mean: %f\tMedian: %f\tMode: %f", mean, median, mode);
}
bool goAgain() {
char *temp;
printf("\nWould you like to play again(Y/N)? ");
scanf("%s", &temp);
while (temp != 'n' && temp != 'N' && temp != 'y' && temp != 'Y') {
printf("\nI am sorry that is invalid -- try again");
printf("\nWould you like to play again(Y/N)? ");
scanf("%s", &temp);
}
if (temp == 'y' || temp == 'Y') {
return true;
} else {
return false;
}
}