Yesterday a thread went up with some code asking for help:
"A little help for a new guy? Functions problem! "
I have re-written all the code and it nows works properly for all modes of operation required ( although the code maybe messy, I'm still learning ).
The only problem is is that the request was in C++ and I only know C. I've re-written the program in C and was hoping someone could just change it to C++ for him. I've done the leg work it just needs a cosmetic work over.
Code:
//Made By: Chris M 9/12/2002
//This program gathers a list from the user and returns
//a median and an average from them.
//Drastically reformatted to work by Craig Evans ( Crag2804 )
#include <stdio.h>
#include <stdlib.h>
#define SWAP(a,b) { int t; t=a; a=b; b=t; } // Macro for swapping
void bubble_srt(int a[], int n);
float f_med(int a[]);
int num = 0,*ptr;
int main()
{
float mean = 0,sum = 0, answer = 0;
int i;
char choose = 'm';
printf("This program will ask the user for a list of numbers.\n");
printf("Then calculate the median or mean average.\n\n");
printf("How many numbers are you going to put in?\n: ");
scanf("%d",&num);
ptr = (int*) calloc ( num, sizeof (int)); //Creates enough room for the array
if (ptr == NULL) printf("Calloc failed");
else {
for (i=0;i<num;i++) { //Fills the array with inputted values
printf("Number %d: ",(i+1));
scanf("%d",&ptr[i]);
}
while (choose != 'q') {
while (getchar() != '\n') {}
printf("Choose from the following set of options:\n");
printf("Get the (m)edian, (a)verage, or (q)uit?: ");
scanf("%c",&choose);
switch (choose) {
case 'm':
bubble_srt(ptr, num);
printf("\nAfter sorting your numbers are:\n");
for (i=0;i<num;i++)
printf("Number %d: %d\n",(i+1),ptr[i]);
answer = f_med (ptr);
printf("The median for your set of numbers will be:%f\n",answer);
break;
case 'a':
for (i=0;i<num;i++) {
sum += ptr[i];};
mean = (sum/num);
printf("\nThe mean average for your data set is:%2.2f\n\n",mean);
break;
default:
break;
}
}
}
return 0;
}
void bubble_srt(int a[], int n) {
int i, j;
for(i = 0; i < n; i++)
{
for(j = 1; j < (n-i); j++)
{
if(a[j-1] > a[j])
SWAP(a[j-1],a[j]);
}
}
}
float f_med (int a[]) {
int odd= (num / 2);
float even,neven,average;
if ( (num%2) != 0 ) {
return ptr[odd];}
else {
even = (num/2);
neven = (even + 1);
average = (even + neven)/2;
return average;
}
}
Thanks