Charles Tritt
/
FuncSumEx
Diff: main.cpp
- Revision:
- 0:78eefa5ae28e
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Fri Oct 06 03:20:11 2017 +0000 @@ -0,0 +1,62 @@ +/* + Program 8.3 Calculating an average using functions. + from Horton's Beginning C, 5th ed. + + Note isolation of user input in main and a single function. + + Ported to mbed by C. S. Tritt + Last revised: 10/5/17 (v. 1.0) +*/ +#include "mbed.h" + +const int MAX_COUNT=10; // Set input limit. Protects against buffer overrun. + +// Function prototypes... +float Sum(float x[], int n); // Sums the values in a float array. +float Average(float x[], int n); // Averages the values in a float array. +int GetData(float *data, int max_count); // Gets data from std Serial. + +// main program - execution starts here. +int main(void) { + float samples[MAX_COUNT] = {0.0}; // Create array for samples. + int sampleCount = GetData(samples, MAX_COUNT); // Get values. + float average = Average(samples, sampleCount); // Find average. + // Display results. + printf("The average of the values you entered is: %.2f.\n", average); + return 0; +} + +// Function to calculate the sum of array elements. n is the number of elements +// in array x. +float Sum(float x[], int n) { + float sum = 0.0; + for(int i = 0 ; i < n ; ++i) sum += x[i]; + return sum; +} + +// Function to calculate the average of array elements. Calls Sum. +float Average(float x[], int n) { + return Sum(x, n)/n; +} + +// Function to read in data items and store in data array. The function returns +// the number of items stored. +int GetData(float *data, int max_count) { + int nValues = 0; + // Clear screen & move cursor to upper left ANSI/VT100 sequence. + const char ESC=27; printf("%c[2J", ESC); printf("%c[H", ESC); + printf("Assure Local Echo is activated!\n"); + printf("Number of values to average (Maximum %d)? ", max_count); + scanf("%d", &nValues); + printf("%d was read.\n", nValues); // added by cst. + if(nValues > max_count) { + printf("Maximum count exceeded. %d items will be read.", max_count); + nValues = max_count; + } + printf("Enter values:\n"); + for( int i = 0 ; i < nValues ; ++i) { + scanf("%f", &data[i]); + printf("%f was read.\n", data[i]); // added by cst. + } + return nValues; +} \ No newline at end of file