Hi everyone,
I need some help here. I am working on an assignment -- to write a function that determines the median of a sorted array, and use Pointer Notation whenever possible.
My code is below, and it works, but I don't know how to incorporate the pointer notation in it. I am lost on the subject of pointers, and I hope you folks can help me out. Thank you in advance.
CODE
#include <iostream>
using namespace std;
const int MAX_SIZE = 100;
int ArraySize = 0;
//Function Prototypes.
void GetUserInput(double []);
void SortArray(double []);
void ShowMedian(double []);
int main()
{
//This is the exit condition.
bool exit = false;
double numbers[MAX_SIZE];
char action;
GetUserInput(numbers);
do
{
cout << "\nPlease select action\n"
//These are the menu choices.
"1) Show the median\n"
"2) Input new numbers\n"
"3) Exit the program! ";
cin.get(action);
getchar();
if(action == '1')
ShowMedian(numbers);
else if(action == '2')
GetUserInput(numbers);
else if(action == '3')
exit = true;
else
cout << "\n\nInvalid action\n\n";
}while(!exit);
//Pause the system to display the results.
system("\nPause");
}
//The GetUserInput function will get the user's input from the keyboard.
void GetUserInput(double numbers[MAX_SIZE])
{
//The exit the program condition.
bool exit = false;
//Clear the array so that new numbers can be entered.
for(int i=0; i < MAX_SIZE; i++)
numbers[i] = 0;
//Using a do-while loop to ask the user to enter the number of numbers
//that she wishes to enter.
do
{
cout << "\nHow many numbers are you going to enter? > ";
cin >> ArraySize;
//Capture the enter key.
getchar();
if(ArraySize > MAX_SIZE || ArraySize == 0)
cout << "\nInvalid number\n";
}while(ArraySize == 0 || ArraySize > MAX_SIZE);
//Ask the user to enter positive numbers.
for(int i = 0; i < ArraySize; i++)
{
cout << "\nPlease enter a positive number: ";
cin >> numbers[i];
getchar();
}
}
//The ShowMedian function will take an array of numbers, and an integer
//indicating the size of the array and then return the median of the values
//in the array.
void ShowMedian(double numbers[MAX_SIZE])
{
SortArray(numbers);
int medIndex = 0;
double median = 0;
//If median is 1/2 way between.
if((ArraySize % 2) != 0)
{
medIndex = ((ArraySize-1) / 2);
median = numbers[medIndex];
}
else
{
medIndex = ArraySize / 2;
median = ((numbers[medIndex] + numbers[medIndex +1 ])/2);
}
cout << "\nThe median is: " << median << endl;
}
//The SortArray function will sort the array in order.
void SortArray(double nums[])
{
int i, med;
double brief;
for (i = ArraySize-1; i >= 0; i--)
{
for (med = 1; med <= i; med++)
{
if (nums[med-1] > nums[med])
{
brief = nums[med-1];
nums[med-1] = nums[med];
nums[med] = brief;
}
}
}
}